home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / FAQs / netfaqs / C-faq < prev    next >
Text File  |  1994-08-01  |  145KB  |  3,781 lines

  1.  
  2. Newsgroups: comp.lang.c,comp.answers,news.answers
  3. From: scs@eskimo.com (Steve Summit)
  4. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  5. Date: 1 Apr 94 11:04:00 GMT
  6. Expires: Tue, 3 May 1994 00:00:00 GMT
  7. Followup-To: poster
  8. Organization: none, at the moment
  9. Lines: 3765
  10. Approved: news-answers-request@MIT.Edu
  11. Supersedes: <1994Mar02.0102.scs.0002@eskimo.com>
  12. X-Archive-Name: C-faq/faq
  13. X-Last-Modified: March 1, 1994
  14. Xref: bloom-beacon.mit.edu comp.lang.c:37506 comp.answers:4382 news.answers:17167
  15.  
  16. Archive-name: C-faq/faq
  17. Comp-lang-c-archive-name: C-FAQ-list
  18.  
  19. [Last modified March 1, 1994 by scs.]
  20.  
  21. Certain topics come up again and again on this newsgroup.  They are good
  22. questions, and the answers may not be immediately obvious, but each time
  23. they recur, much net bandwidth and reader time is wasted on repetitive
  24. responses, and on tedious corrections to the incorrect answers which are
  25. inevitably posted.
  26.  
  27. This article, which is posted monthly, attempts to answer these common
  28. questions definitively and succinctly, so that net discussion can move
  29. on to more constructive topics without continual regression to first
  30. principles.
  31.  
  32. No mere newsgroup article can substitute for thoughtful perusal of a
  33. full-length tutorial or language reference manual.  Anyone interested
  34. enough in C to be following this newsgroup should also be interested
  35. enough to read and study one or more such manuals, preferably several
  36. times.  Some C books and compiler manuals are unfortunately inadequate;
  37. a few even perpetuate some of the myths which this article attempts to
  38. refute.  Several noteworthy books on C are listed in this article's
  39. bibliography.  Many of the questions and answers are cross-referenced to
  40. these books, for further study by the interested and dedicated reader
  41. (but beware of ANSI vs. ISO C Standard section numbers; see question
  42. 5.1).
  43.  
  44. If you have a question about C which is not answered in this article,
  45. first try to answer it by checking a few of the referenced books, or by
  46. asking knowledgeable colleagues, before posing your question to the net
  47. at large.  There are many people on the net who are happy to answer
  48. questions, but the volume of repetitive answers posted to one question,
  49. as well as the growing number of questions as the net attracts more
  50. readers, can become oppressive.  If you have questions or comments
  51. prompted by this article, please reply by mail rather than following up
  52. -- this article is meant to decrease net traffic, not increase it.
  53.  
  54. Besides listing frequently-asked questions, this article also summarizes
  55. frequently-posted answers.  Even if you know all the answers, it's worth
  56. skimming through this list once in a while, so that when you see one of
  57. its questions unwittingly posted, you won't have to waste time
  58. answering.
  59.  
  60. This article is always being improved.  Your input is welcomed.  Send
  61. your comments to scs@eskimo.com .
  62.  
  63. The questions answered here are divided into several categories:
  64.  
  65.      1. Null Pointers
  66.      2. Arrays and Pointers
  67.      3. Memory Allocation
  68.      4. Expressions
  69.      5. ANSI C
  70.      6. C Preprocessor
  71.      7. Variable-Length Argument Lists
  72.      8. Boolean Expressions and Variables
  73.      9. Structs, Enums, and Unions
  74.     10. Declarations
  75.     11. Stdio
  76.     12. Library Subroutines
  77.     13. Lint
  78.     14. Style
  79.     15. Floating Point
  80.     16. System Dependencies
  81.     17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  82.  
  83. Herewith, some frequently-asked questions and their answers:
  84.  
  85.  
  86. Section 1. Null Pointers
  87.  
  88. 1.1:    What is this infamous null pointer, anyway?
  89.  
  90. A:    The language definition states that for each pointer type, there
  91.     is a special value -- the "null pointer" -- which is
  92.     distinguishable from all other pointer values and which is not
  93.     the address of any object or function.  That is, the address-of
  94.     operator & will never yield a null pointer, nor will a
  95.     successful call to malloc.  (malloc returns a null pointer when
  96.     it fails, and this is a typical use of null pointers: as a
  97.     "special" pointer value with some other meaning, usually "not
  98.     allocated" or "not pointing anywhere yet.")
  99.  
  100.     A null pointer is conceptually different from an uninitialized
  101.     pointer.  A null pointer is known not to point to any object; an
  102.     uninitialized pointer might point anywhere.  See also questions
  103.     3.1, 3.13, and 17.1.
  104.  
  105.     As mentioned in the definition above, there is a null pointer
  106.     for each pointer type, and the internal values of null pointers
  107.     for different types may be different.  Although programmers need
  108.     not know the internal values, the compiler must always be
  109.     informed which type of null pointer is required, so it can make
  110.     the distinction if necessary (see below).
  111.  
  112.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  113.     Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  114.  
  115. 1.2:    How do I "get" a null pointer in my programs?
  116.  
  117. A:    According to the language definition, a constant 0 in a pointer
  118.     context is converted into a null pointer at compile time.  That
  119.     is, in an initialization, assignment, or comparison when one
  120.     side is a variable or expression of pointer type, the compiler
  121.     can tell that a constant 0 on the other side requests a null
  122.     pointer, and generate the correctly-typed null pointer value.
  123.     Therefore, the following fragments are perfectly legal:
  124.  
  125.         char *p = 0;
  126.         if(p != 0)
  127.  
  128.     However, an argument being passed to a function is not
  129.     necessarily recognizable as a pointer context, and the compiler
  130.     may not be able to tell that an unadorned 0 "means" a null
  131.     pointer.  For instance, the Unix system call "execl" takes a
  132.     variable-length, null-pointer-terminated list of character
  133.     pointer arguments.  To generate a null pointer in a function
  134.     call context, an explicit cast is typically required, to force
  135.     the 0 to be in a pointer context:
  136.  
  137.         execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  138.  
  139.     If the (char *) cast were omitted, the compiler would not know
  140.     to pass a null pointer, and would pass an integer 0 instead.
  141.     (Note that many Unix manuals get this example wrong.)
  142.  
  143.     When function prototypes are in scope, argument passing becomes
  144.     an "assignment context," and most casts may safely be omitted,
  145.     since the prototype tells the compiler that a pointer is
  146.     required, and of which type, enabling it to correctly convert
  147.     unadorned 0's.  Function prototypes cannot provide the types for
  148.     variable arguments in variable-length argument lists, however,
  149.     so explicit casts are still required for those arguments.  It is
  150.     safest always to cast null pointer function arguments, to guard
  151.     against varargs functions or those without prototypes, to allow
  152.     interim use of non-ANSI compilers, and to demonstrate that you
  153.     know what you are doing.  (Incidentally, it's also a simpler
  154.     rule to remember.)
  155.  
  156.     Summary:
  157.  
  158.         Unadorned 0 okay:    Explicit cast required:
  159.  
  160.         initialization        function call,
  161.                     no prototype in scope
  162.         assignment
  163.                     variable argument in
  164.         comparison        varargs function call
  165.  
  166.         function call,
  167.         prototype in scope,
  168.         fixed argument
  169.  
  170.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  171.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  172.     Sec. 3.2.2.3 .
  173.  
  174. 1.3:    What is NULL and how is it #defined?
  175.  
  176. A:    As a matter of style, many people prefer not to have unadorned
  177.     0's scattered throughout their programs.  For this reason, the
  178.     preprocessor macro NULL is #defined (by <stdio.h> or
  179.     <stddef.h>), with value 0 (or (void *)0, about which more
  180.     later).  A programmer who wishes to make explicit the
  181.     distinction between 0 the integer and 0 the null pointer can
  182.     then use NULL whenever a null pointer is required.  This is a
  183.     stylistic convention only; the preprocessor turns NULL back to 0
  184.     which is then recognized by the compiler (in pointer contexts)
  185.     as before.  In particular, a cast may still be necessary before
  186.     NULL (as before 0) in a function call argument.  (The table
  187.     under question 1.2 above applies for NULL as well as 0.)
  188.  
  189.     NULL should _only_ be used for pointers; see question 1.8.
  190.  
  191.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  192.     Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  193.     Rationale Sec. 4.1.5 p. 74.
  194.  
  195. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  196.     bit pattern as the internal representation of a null pointer?
  197.  
  198. A:    Programmers should never need to know the internal
  199.     representation(s) of null pointers, because they are normally
  200.     taken care of by the compiler.  If a machine uses a nonzero bit
  201.     pattern for null pointers, it is the compiler's responsibility
  202.     to generate it when the programmer requests, by writing "0" or
  203.     "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  204.     machine for which internal null pointers are nonzero is as valid
  205.     as on any other, because the compiler must (and can) still
  206.     generate the machine's correct null pointers in response to
  207.     unadorned 0's seen in pointer contexts.
  208.  
  209. 1.5:    If NULL were defined as follows:
  210.  
  211.         #define NULL (char *)0
  212.  
  213.     wouldn't that make function calls which pass an uncast NULL
  214.     work?
  215.  
  216. A:    Not in general.  The problem is that there are machines which
  217.     use different internal representations for pointers to different
  218.     types of data.  The suggested #definition would make uncast NULL
  219.     arguments to functions expecting pointers to characters to work
  220.     correctly, but pointer arguments to other types would still be
  221.     problematical, and legal constructions such as
  222.  
  223.         FILE *fp = NULL;
  224.  
  225.     could fail.
  226.  
  227.     Nevertheless, ANSI C allows the alternate
  228.  
  229.         #define NULL ((void *)0)
  230.  
  231.     definition for NULL.  Besides helping incorrect programs to work
  232.     (but only on machines with homogeneous pointers, thus
  233.     questionably valid assistance) this definition may catch
  234.     programs which use NULL incorrectly (e.g. when the ASCII  NUL
  235.     character was really intended; see question 1.8).
  236.  
  237.     References: ANSI Rationale Sec. 4.1.5 p. 74.
  238.  
  239. 1.6:    I use the preprocessor macro
  240.  
  241.         #define Nullptr(type) (type *)0
  242.  
  243.     to help me build null pointers of the correct type.
  244.  
  245. A:    This trick, though popular in some circles, does not buy much.
  246.     It is not needed in assignments and comparisons; see question
  247.     1.2.  It does not even save keystrokes.  Its use suggests to the
  248.     reader that the author is shaky on the subject of null pointers,
  249.     and requires the reader to check the #definition of the macro,
  250.     its invocations, and _all_ other pointer usages much more
  251.     carefully.  See also question 8.1.
  252.  
  253. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  254.     null pointers valid?  What if the internal representation for
  255.     null pointers is nonzero?
  256.  
  257. A:    When C requires the boolean value of an expression (in the if,
  258.     while, for, and do statements, and with the &&, ||, !, and ?:
  259.     operators), a false value is produced when the expression
  260.     compares equal to zero, and a true value otherwise.  That is,
  261.     whenever one writes
  262.  
  263.         if(expr)
  264.  
  265.     where "expr" is any expression at all, the compiler essentially
  266.     acts as if it had been written as
  267.  
  268.         if(expr != 0)
  269.  
  270.     Substituting the trivial pointer expression "p" for "expr," we
  271.     have
  272.  
  273.         if(p)    is equivalent to        if(p != 0)
  274.  
  275.     and this is a comparison context, so the compiler can tell that
  276.     the (implicit) 0 is a null pointer, and use the correct value.
  277.     There is no trickery involved here; compilers do work this way,
  278.     and generate identical code for both statements.  The internal
  279.     representation of a pointer does _not_ matter.
  280.  
  281.     The boolean negation operator, !, can be described as follows:
  282.  
  283.         !expr    is essentially equivalent to    expr?0:1
  284.  
  285.     It is left as an exercise for the reader to show that
  286.  
  287.         if(!p)    is equivalent to        if(p == 0)
  288.  
  289.     "Abbreviations" such as if(p), though perfectly legal, are
  290.     considered by some to be bad style.
  291.  
  292.     See also question 8.2.
  293.  
  294.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  295.     Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  296.     3.6.5 .
  297.  
  298. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  299.  
  300. A:    Many programmers believe that "NULL" should be used in all
  301.     pointer contexts, as a reminder that the value is to be thought
  302.     of as a pointer.  Others feel that the confusion surrounding
  303.     "NULL" and "0" is only compounded by hiding "0" behind a
  304.     #definition, and prefer to use unadorned "0" instead.  There is
  305.     no one right answer.  C programmers must understand that "NULL"
  306.     and "0" are interchangeable and that an uncast "0" is perfectly
  307.     acceptable in initialization, assignment, and comparison
  308.     contexts.  Any usage of "NULL" (as opposed to "0") should be
  309.     considered a gentle reminder that a pointer is involved;
  310.     programmers should not depend on it (either for their own
  311.     understanding or the compiler's) for distinguishing pointer 0's
  312.     from integer 0's.
  313.  
  314.     NULL should _not_ be used when another kind of 0 is required,
  315.     even though it might work, because doing so sends the wrong
  316.     stylistic message.  (ANSI allows the #definition of NULL to be
  317.     (void *)0, which will not work in non-pointer contexts.)  In
  318.     particular, do not use NULL when the ASCII null character (NUL)
  319.     is desired.  Provide your own definition
  320.  
  321.         #define NUL '\0'
  322.  
  323.     if you must.
  324.  
  325.     References: K&R II Sec. 5.4 p. 102.
  326.  
  327. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  328.     the value of NULL changes, perhaps on a machine with nonzero
  329.     null pointers?
  330.  
  331. A:    No.  Although symbolic constants are often used in place of
  332.     numbers because the numbers might change, this is _not_ the
  333.     reason that NULL is used in place of 0.  Once again, the
  334.     language guarantees that source-code 0's (in pointer contexts)
  335.     generate null pointers.  NULL is used only as a stylistic
  336.     convention.
  337.  
  338. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  339.     is not?
  340.  
  341. A:    When the term "null" or "NULL" is casually used, one of several
  342.     things may be meant:
  343.  
  344.     1.    The conceptual null pointer, the abstract language
  345.         concept defined in question 1.1.  It is implemented
  346.         with...
  347.  
  348.     2.    The internal (or run-time) representation of a null
  349.         pointer, which may or may not be all-bits-0 and which
  350.         may be different for different pointer types.  The
  351.         actual values should be of concern only to compiler
  352.         writers.  Authors of C programs never see them, since
  353.         they use...
  354.  
  355.     3.    The source code syntax for null pointers, which is the
  356.         single character "0".  It is often hidden behind...
  357.  
  358.     4.    The NULL macro, which is #defined to be "0" or
  359.         "(void *)0".  Finally, as red herrings, we have...
  360.  
  361.     5.    The ASCII null character (NUL), which does have all bits
  362.         zero, but has no necessary relation to the null pointer
  363.         except in name; and...
  364.  
  365.     6.    The "null string," which is another name for an empty
  366.         string ("").  The term "null string" can be confusing in
  367.         C (and should perhaps be avoided), because it involves a
  368.         null ('\0') character, but not a null pointer, which
  369.         brings us full circle...
  370.  
  371.     This article always uses the phrase "null pointer" (in lower
  372.     case) for sense 1, the character "0" for sense 3, and the
  373.     capitalized word "NULL" for sense 4.
  374.  
  375. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  376.     do these questions come up so often?
  377.  
  378. A:    C programmers traditionally like to know more than they need to
  379.     about the underlying machine implementation.  The fact that null
  380.     pointers are represented both in source code, and internally to
  381.     most machines, as zero invites unwarranted assumptions.  The use
  382.     of a preprocessor macro (NULL) suggests that the value might
  383.     change later, or on some weird machine.  The construct
  384.     "if(p == 0)" is easily misread as calling for conversion of p to
  385.     an integral type, rather than 0 to a pointer type, before the
  386.     comparison.  Finally, the distinction between the several uses
  387.     of the term "null" (listed above) is often overlooked.
  388.  
  389.     One good way to wade out of the confusion is to imagine that C
  390.     had a keyword (perhaps "nil", like Pascal) with which null
  391.     pointers were requested.  The compiler could either turn "nil"
  392.     into the correct type of null pointer, when it could determine
  393.     the type from the source code, or complain when it could not.
  394.     Now, in fact, in C the keyword for a null pointer is not "nil"
  395.     but "0", which works almost as well, except that an uncast "0"
  396.     in a non-pointer context generates an integer zero instead of an
  397.     error message, and if that uncast 0 was supposed to be a null
  398.     pointer, the code may not work.
  399.  
  400. 1.12:    I'm still confused.  I just can't understand all this null
  401.     pointer stuff.
  402.  
  403. A:    Follow these two simple rules:
  404.  
  405.     1.    When you want to refer to a null pointer in source code,
  406.         use "0" or "NULL".
  407.  
  408.     2.    If the usage of "0" or "NULL" is an argument in a
  409.         function call, cast it to the pointer type expected by
  410.         the function being called.
  411.  
  412.     The rest of the discussion has to do with other people's
  413.     misunderstandings, or with the internal representation of null
  414.     pointers (which you shouldn't need to know), or with ANSI C
  415.     refinements.  Understand questions 1.1, 1.2, and 1.3, and
  416.     consider 1.8 and 1.11, and you'll do fine.
  417.  
  418. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  419.     be easier simply to require them to be represented internally by
  420.     zeroes?
  421.  
  422. A:    If for no other reason, doing so would be ill-advised because it
  423.     would unnecessarily constrain implementations which would
  424.     otherwise naturally represent null pointers by special, nonzero
  425.     bit patterns, particularly when those values would trigger
  426.     automatic hardware traps for invalid accesses.
  427.  
  428.     Besides, what would this requirement really accomplish?  Proper
  429.     understanding of null pointers does not require knowledge of the
  430.     internal representation, whether zero or nonzero.  Assuming that
  431.     null pointers are internally zero does not make any code easier
  432.     to write (except for a certain ill-advised usage of calloc; see
  433.     question 3.13).  Known-zero internal pointers would not obviate
  434.     casts in function calls, because the _size_ of the pointer might
  435.     still be different from that of an int.  (If "nil" were used to
  436.     request null pointers rather than "0," as mentioned in question
  437.     1.11, the urge to assume an internal zero representation would
  438.     not even arise.)
  439.  
  440. 1.14:    Seriously, have any actual machines really used nonzero null
  441.     pointers, or different representations for pointers to different
  442.     types?
  443.  
  444. A:    The Prime 50 series used segment 07777, offset 0 for the null
  445.     pointer, at least for PL/I.  Later models used segment 0, offset
  446.     0 for null pointers in C, necessitating new instructions such as
  447.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  448.     poorly-written C code which made incorrect assumptions.  Older,
  449.     word-addressed Prime machines were also notorious for requiring
  450.     larger byte pointers (char *'s) than word pointers (int *'s).
  451.  
  452.     The Eclipse MV series from Data General has three
  453.     architecturally supported pointer formats (word, byte, and bit
  454.     pointers), two of which are used by C compilers: byte pointers
  455.     for char * and void *, and word pointers for everything else.
  456.  
  457.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  458.     (internal) null pointers.
  459.  
  460.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  461.     ring, segment, and offset.  Most users (in ring 11) have null
  462.     pointers of 0xB00000000000.
  463.  
  464.     The Symbolics Lisp Machine, a tagged architecture, does not even
  465.     have conventional numeric pointers; it uses the pair <NIL, 0>
  466.     (basically a nonexistent <object, offset> handle) as a C null
  467.     pointer.
  468.  
  469.     Depending on the "memory model" in use, 80*86 processors (PC's)
  470.     may use 16 bit data pointers and 32 bit function pointers, or
  471.     vice versa.
  472.  
  473.     The old HP 3000 series computers use a different addressing
  474.     scheme for byte addresses than for word addresses; void and char
  475.     pointers therefore have a different representation than an int
  476.     (structure, etc.) pointer to the same address would have.
  477.  
  478. 1.15:    What does a run-time "null pointer assignment" error mean?  How
  479.     do I track it down?
  480.  
  481. A:    This message, which occurs only under MS-DOS (see, therefore,
  482.     section 16) means that you've written, via a null pointer, to
  483.     location zero.
  484.  
  485.     A debugger will usually let you set a data breakpoint on
  486.     location 0.  Alternately, you could write a bit of code to copy
  487.     20 or so bytes from location 0 into another buffer, and
  488.     periodically check that it hasn't changed.
  489.  
  490.  
  491. Section 2. Arrays and Pointers
  492.  
  493. 2.1:    I had the definition char a[6] in one source file, and in
  494.     another I declared extern char *a.  Why didn't it work?
  495.  
  496. A:    The declaration extern char *a simply does not match the actual
  497.     definition.  The type "pointer-to-type-T" is not the same as
  498.     "array-of-type-T."  Use extern char a[].
  499.  
  500.     References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  501.  
  502. 2.2:    But I heard that char a[] was identical to char *a.
  503.  
  504. A:    Not at all.  (What you heard has to do with formal parameters to
  505.     functions; see question 2.4.)  Arrays are not pointers.  The
  506.     array declaration "char a[6];" requests that space for six
  507.     characters be set aside, to be known by the name "a."  That is,
  508.     there is a location named "a" at which six characters can sit.
  509.     The pointer declaration "char *p;" on the other hand, requests a
  510.     place which holds a pointer.  The pointer is to be known by the
  511.     name "p," and can point to any char (or contiguous array of
  512.     chars) anywhere.
  513.  
  514.     As usual, a picture is worth a thousand words.  The statements
  515.  
  516.         char a[] = "hello";
  517.         char *p = "world";
  518.  
  519.     would result in data structures which could be represented like
  520.     this:
  521.  
  522.            +---+---+---+---+---+---+
  523.         a: | h | e | l | l | o |\0 |
  524.            +---+---+---+---+---+---+
  525.  
  526.            +-----+     +---+---+---+---+---+---+
  527.         p: |  *======> | w | o | r | l | d |\0 |
  528.            +-----+     +---+---+---+---+---+---+
  529.  
  530.     It is important to realize that a reference like x[3] generates
  531.     different code depending on whether x is an array or a pointer.
  532.     Given the declarations above, when the compiler sees the
  533.     expression a[3], it emits code to start at the location "a,"
  534.     move three past it, and fetch the character there.  When it sees
  535.     the expression p[3], it emits code to start at the location "p,"
  536.     fetch the pointer value there, add three to the pointer, and
  537.     finally fetch the character pointed to.  In the example above,
  538.     both a[3] and p[3] happen to be the character 'l', but the
  539.     compiler gets there differently.  (See also questions 17.19 and
  540.     17.20.)
  541.  
  542. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  543.     C?
  544.  
  545. A:    Much of the confusion surrounding pointers in C can be traced to
  546.     a misunderstanding of this statement.  Saying that arrays and
  547.     pointers are "equivalent" neither means that they are identical
  548.     nor even interchangeable.
  549.  
  550.     "Equivalence" refers to the following key definition:
  551.  
  552.         An lvalue [see question 2.5] of type array-of-T
  553.         which appears in an expression decays (with
  554.         three exceptions) into a pointer to its first
  555.         element; the type of the resultant pointer is
  556.         pointer-to-T.
  557.  
  558.     (The exceptions are when the array is the operand of a sizeof or
  559.     & operator, or is a literal string initializer for a character
  560.     array.)
  561.  
  562.     As a consequence of this definition, there is no apparent
  563.     difference in the behavior of the "array subscripting" operator
  564.     [] as it applies to arrays and pointers.  In an expression of
  565.     the form a[i], the array reference "a" decays into a pointer,
  566.     following the rule above, and is then subscripted just as would
  567.     be a pointer variable in the expression p[i] (although the
  568.     eventual memory accesses will be different, as explained in
  569.     question 2.2).  In either case, the expression x[i] (where x is
  570.     an array or a pointer) is, by definition, identical to
  571.     *((x)+(i)).
  572.  
  573.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  574.     Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  575.  
  576. 2.4:    Then why are array and pointer declarations interchangeable as
  577.     function formal parameters?
  578.  
  579. A:    Since arrays decay immediately into pointers, an array is never
  580.     actually passed to a function.  As a convenience, any parameter
  581.     declarations which "look like" arrays, e.g.
  582.  
  583.         f(a)
  584.         char a[];
  585.  
  586.     are treated by the compiler as if they were pointers, since that
  587.     is what the function will receive if an array is passed:
  588.  
  589.         f(a)
  590.         char *a;
  591.  
  592.     This conversion holds only within function formal parameter
  593.     declarations, nowhere else.  If this conversion bothers you,
  594.     avoid it; many people have concluded that the confusion it
  595.     causes outweighs the small advantage of having the declaration
  596.     "look like" the call and/or the uses within the function.
  597.  
  598.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  599.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  600.     Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  601.     pp. 33-4.
  602.  
  603. 2.5:    How can an array be an lvalue, if you can't assign to it?
  604.  
  605. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  606.     array is not.
  607.  
  608.     References: ANSI Sec. 3.2.2.1 p. 37.
  609.  
  610. 2.6:    Why doesn't sizeof properly report the size of an array which is
  611.     a parameter to a function?
  612.  
  613. A:    The sizeof operator reports the size of the pointer parameter
  614.     which the function actually receives (see question 2.4).
  615.  
  616. 2.7:    Someone explained to me that arrays were really just constant
  617.     pointers.
  618.  
  619. A:    This is a bit of an oversimplification.  An array name is
  620.     "constant" in that it cannot be assigned to, but an array is
  621.     _not_ a pointer, as the discussion and pictures in question 2.2
  622.     should make clear.
  623.  
  624. 2.8:    Practically speaking, what is the difference between arrays and
  625.     pointers?
  626.  
  627. A:    Arrays automatically allocate space, but can't be relocated or
  628.     resized.  Pointers must be explicitly assigned to point to
  629.     allocated space (perhaps using malloc), but can be reassigned
  630.     (i.e. pointed at different objects) at will, and have many other
  631.     uses besides serving as the base of blocks of memory.
  632.  
  633.     Due to the so-called equivalence of arrays and pointers (see
  634.     question 2.3), arrays and pointers often seem interchangeable,
  635.     and in particular a pointer to a block of memory assigned by
  636.     malloc is frequently treated (and can be referenced using []
  637.     exactly) as if it were a true array.  (See question 2.14; see
  638.     also question 17.20.)
  639.  
  640. 2.9:    I came across some "joke" code containing the "expression"
  641.     5["abcdef"] .  How can this be legal C?
  642.  
  643. A:    Yes, Virginia, array subscripting is commutative in C.  This
  644.     curious fact follows from the pointer definition of array
  645.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  646.     _any_ expression e and primary expression a, as long as one of
  647.     them is a pointer expression and one is integral.  This
  648.     unsuspected commutativity is often mentioned in C texts as if it
  649.     were something to be proud of, but it finds no useful
  650.     application outside of the Obfuscated C Contest (see question
  651.     17.13).
  652.  
  653.     References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  654.  
  655. 2.10:    My compiler complained when I passed a two-dimensional array to
  656.     a routine expecting a pointer to a pointer.
  657.  
  658. A:    The rule by which arrays decay into pointers is not applied
  659.     recursively.  An array of arrays (i.e. a two-dimensional array
  660.     in C) decays into a pointer to an array, not a pointer to a
  661.     pointer.  Pointers to arrays can be confusing, and must be
  662.     treated carefully.  (The confusion is heightened by the
  663.     existence of incorrect compilers, including some versions of pcc
  664.     and pcc-derived lint's, which improperly accept assignments of
  665.     multi-dimensional arrays to multi-level pointers.)  If you are
  666.     passing a two-dimensional array to a function:
  667.  
  668.         int array[NROWS][NCOLUMNS];
  669.         f(array);
  670.  
  671.     the function's declaration should match:
  672.  
  673.         f(int a[][NCOLUMNS]) {...}
  674.     or
  675.         f(int (*ap)[NCOLUMNS]) {...}    /* ap is a pointer to an array */
  676.  
  677.     In the first declaration, the compiler performs the usual
  678.     implicit parameter rewriting of "array of array" to "pointer to
  679.     array;" in the second form the pointer declaration is explicit.
  680.     Since the called function does not allocate space for the array,
  681.     it does not need to know the overall size, so the number of
  682.     "rows," NROWS, can be omitted.  The "shape" of the array is
  683.     still important, so the "column" dimension NCOLUMNS (and, for 3-
  684.     or more dimensional arrays, the intervening ones) must be
  685.     included.
  686.  
  687.     If a function is already declared as accepting a pointer to a
  688.     pointer, it is probably incorrect to pass a two-dimensional
  689.     array directly to it.
  690.  
  691.     References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  692.  
  693. 2.11:    How do I write functions which accept 2-dimensional arrays when
  694.     the "width" is not known at compile time?
  695.  
  696. A:    It's not easy.  One way is to pass in a pointer to the [0][0]
  697.     element, along with the two dimensions, and simulate array
  698.     subscripting "by hand:"
  699.  
  700.         f2(aryp, nrows, ncolumns)
  701.         int *aryp;
  702.         int nrows, ncolumns;
  703.         { ... ary[i][j] is really aryp[i * ncolumns + j] ... }
  704.  
  705.     This function could be called with the array from question 2.10
  706.     as
  707.  
  708.         f2(&array[0][0], NROWS, NCOLUMNS);
  709.  
  710.     It must be noted, however, that a program which performs
  711.     multidimensional array subscripting "by hand" in this way is not
  712.     in strict conformance with the ANSI C Standard; the behavior of
  713.     accessing (&array[0][0])[x] is not defined for x > NCOLUMNS.
  714.  
  715.     gcc allows local arrays to be declared having sizes which are
  716.     specified by a function's arguments, but this is a nonstandard
  717.     extension.
  718.  
  719.     See also question 2.15.
  720.  
  721. 2.12:    How do I declare a pointer to an array?
  722.  
  723. A:    Usually, you don't want to.  When people speak casually of a
  724.     pointer to an array, they usually mean a pointer to its first
  725.     element.
  726.  
  727.     Instead of a pointer to an array, consider using a pointer to
  728.     one of the array's elements.  Arrays of type T decay into
  729.     pointers to type T (see question 2.3), which is convenient;
  730.     subscripting or incrementing the resultant pointer accesses the
  731.     individual members of the array.  True pointers to arrays, when
  732.     subscripted or incremented, step over entire arrays, and are
  733.     generally only useful when operating on arrays of arrays, if at
  734.     all.  (See question 2.10 above.)
  735.  
  736.     If you really need to declare a pointer to an entire array, use
  737.     something like "int (*ap)[N];" where N is the size of the array.
  738.     (See also question 10.4.)  If the size of the array is unknown,
  739.     N can be omitted, but the resulting type, "pointer to array of
  740.     unknown size," is useless.
  741.  
  742. 2.13:    Since array references decay to pointers, given
  743.  
  744.         int array[NROWS][NCOLUMNS];
  745.  
  746.     what's the difference between array and &array?
  747.  
  748. A:    Under ANSI/ISO Standard C, &array yields a pointer, of type
  749.     pointer-to-array-of-T, to the entire array (see also question
  750.     2.12).  Under pre-ANSI C, the & in &array generally elicited a
  751.     warning, and was generally ignored.  Under all C compilers, an
  752.     unadorned reference to an array yields a pointer, of type
  753.     pointer-to-T, to the array's first element.  (See also question
  754.     2.3.)
  755.  
  756. 2.14:    How can I dynamically allocate a multidimensional array?
  757.  
  758. A:    It is usually best to allocate an array of pointers, and then
  759.     initialize each pointer to a dynamically-allocated "row."  Here
  760.     is a two-dimensional example:
  761.  
  762.         int **array1 = (int **)malloc(nrows * sizeof(int *));
  763.         for(i = 0; i < nrows; i++)
  764.             array1[i] = (int *)malloc(ncolumns * sizeof(int));
  765.  
  766.     (In "real" code, of course, malloc would be declared correctly,
  767.     and each return value checked.)
  768.  
  769.     You can keep the array's contents contiguous, while making later
  770.     reallocation of individual rows difficult, with a bit of
  771.     explicit pointer arithmetic:
  772.  
  773.         int **array2 = (int **)malloc(nrows * sizeof(int *));
  774.         array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  775.         for(i = 1; i < nrows; i++)
  776.             array2[i] = array2[0] + i * ncolumns;
  777.  
  778.     In either case, the elements of the dynamic array can be
  779.     accessed with normal-looking array subscripts: array[i][j].
  780.  
  781.     If the double indirection implied by the above schemes is for
  782.     some reason unacceptable, you can simulate a two-dimensional
  783.     array with a single, dynamically-allocated one-dimensional
  784.     array:
  785.  
  786.         int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  787.  
  788.     However, you must now perform subscript calculations manually,
  789.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  790.     macro can hide the explicit calculation, but invoking it then
  791.     requires parentheses and commas which don't look exactly like
  792.     multidimensional array subscripts.)
  793.  
  794.     Finally, you can use pointers-to-arrays:
  795.  
  796.         int (*array4)[NCOLUMNS] =
  797.             (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  798.  
  799.     , but the syntax gets horrific and all but one dimension must be
  800.     known at compile time.
  801.  
  802.     With all of these techniques, you may of course need to remember
  803.     to free the arrays (which may take several steps; see question
  804.     3.9) when they are no longer needed, and you cannot necessarily
  805.     intermix the dynamically-allocated arrays with conventional,
  806.     statically-allocated ones (see question 2.15 below, and also
  807.     question 2.10).
  808.  
  809. 2.15:    How can I use statically- and dynamically-allocated
  810.     multidimensional arrays interchangeably when passing them to
  811.     functions?
  812.  
  813. A:    There is no single perfect method.  Given a function f1()
  814.     similar to the f() of question 2.10, the array as declared in
  815.     question 2.10, f2() as declared in question 2.11, array1,
  816.     array2, array3, and array4 as declared in question 2.14, and a
  817.     function f3() declared as:
  818.  
  819.         f3(pp, m, n)
  820.         int **pp;
  821.         int m, n;
  822.  
  823.     ; the following calls should work as expected:
  824.  
  825.         f1(array, NROWS, NCOLUMNS);
  826.         f1(array4, nrows, NCOLUMNS);
  827.         f2(&array[0][0], NROWS, NCOLUMNS);
  828.         f2(*array2, nrows, ncolumns);
  829.         f2(array3, nrows, ncolumns);
  830.         f2(*array4, nrows, NCOLUMNS);
  831.         f3(array1, nrows, ncolumns);
  832.         f3(array2, nrows, ncolumns);
  833.  
  834.     The following two calls would probably work, but involve
  835.     questionable casts, and work only if the dynamic ncolumns
  836.     matches the static NCOLUMNS:
  837.  
  838.         f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  839.         f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  840.  
  841.     It must again be noted that passing &array[0][0] to f2() is not
  842.     strictly conforming; see question 2.11.
  843.  
  844.     If you can understand why all of the above calls work and are
  845.     written as they are, and if you understand why the combinations
  846.     that are not listed would not work, then you have a _very_ good
  847.     understanding of arrays and pointers (and several other areas)
  848.     in C.
  849.  
  850. 2.16:    Here's a neat trick: if I write
  851.  
  852.         int realarray[10];
  853.         int *array = &realarray[-1];
  854.  
  855.     I can treat "array" as if it were a 1-based array.
  856.  
  857. A:    Although this technique is attractive (and was used in old
  858.     editions of the book Numerical Recipes in C), it does not
  859.     conform to the C standards.  Pointer arithmetic is defined only
  860.     as long as the pointer points within the same allocated block of
  861.     memory, or to the imaginary "terminating" element one past it;
  862.     otherwise, the behavior is undefined, _even if the pointer is
  863.     not dereferenced_.  The code above could fail if, while
  864.     subtracting the offset, an illegal address were generated
  865.     (perhaps because the address tried to "wrap around" past the
  866.     beginning of some memory segment).
  867.  
  868.     References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
  869.     K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.
  870.  
  871. 2.17:    I passed a pointer to a function which initialized it:
  872.  
  873.         ...
  874.         int *ip;
  875.         f(ip);
  876.         ...
  877.  
  878.         void f(ip)
  879.         int *ip;
  880.         {
  881.             static int dummy = 5;
  882.             ip = &dummy;
  883.         }
  884.  
  885.     , but the pointer in the caller was unchanged.
  886.  
  887. A:    Did the function try to initialize the pointer itself, or just
  888.     what it pointed to?  Remember that arguments in C are passed by
  889.     value.  The called function altered only the passed copy of the
  890.     pointer.  You'll want to pass the address of the pointer (the
  891.     function will end up accepting a pointer-to-a-pointer).
  892.  
  893. 2.18:    I have a char * pointer that happens to point to some ints, and
  894.     I want to step it over them.  Why doesn't
  895.  
  896.         ((int *)p)++;
  897.  
  898.     work?
  899.  
  900. A:    In C, a cast operator does not mean "pretend these bits have a
  901.     different type, and treat them accordingly;" it is a conversion
  902.     operator, and by definition it yields an rvalue, which cannot be
  903.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  904.     derived compilers, and an extension in gcc, that expressions
  905.     such as the above are ever accepted.)  Say what you mean: use
  906.  
  907.         p = (char *)((int *)p + 1);
  908.  
  909.     , or simply
  910.  
  911.         p += sizeof(int);
  912.  
  913.     References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  914.  
  915. 2.19:    Can I use a void ** pointer to pass a generic pointer to a
  916.     function by reference?
  917.  
  918. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  919.     void * acts as a generic pointer only because conversions are
  920.     applied automatically when other pointer types are assigned to
  921.     and from void *'s; these conversions cannot be performed (the
  922.     correct underlying pointer type is not known) if an attempt is
  923.     made to indirect upon a void ** value which points at something
  924.     other than a void *.
  925.  
  926.  
  927. Section 3. Memory Allocation
  928.  
  929. 3.1:    Why doesn't this fragment work?
  930.  
  931.         char *answer;
  932.         printf("Type something:\n");
  933.         gets(answer);
  934.         printf("You typed \"%s\"\n", answer);
  935.  
  936. A:    The pointer variable "answer," which is handed to the gets
  937.     function as the location into which the response should be
  938.     stored, has not been set to point to any valid storage.  That
  939.     is, we cannot say where the pointer "answer" points.  (Since
  940.     local variables are not initialized, and typically contain
  941.     garbage, it is not even guaranteed that "answer" starts out as a
  942.     null pointer.  See question 17.1.)
  943.  
  944.     The simplest way to correct the question-asking program is to
  945.     use a local array, instead of a pointer, and let the compiler
  946.     worry about allocation:
  947.  
  948.         #include <string.h>
  949.  
  950.         char answer[100], *p;
  951.         printf("Type something:\n");
  952.         fgets(answer, sizeof(answer), stdin);
  953.         if((p = strchr(answer, '\n')) != NULL)
  954.             *p = '\0';
  955.         printf("You typed \"%s\"\n", answer);
  956.  
  957.     Note that this example also uses fgets instead of gets (always a
  958.     good idea; see question 11.5), allowing the size of the array to
  959.     be specified, so that the end of the array will not be
  960.     overwritten if the user types an overly-long line.
  961.     (Unfortunately for this example, fgets does not automatically
  962.     delete the trailing \n, as gets would.)  It would also be
  963.     possible to use malloc to allocate the answer buffer.
  964.  
  965. 3.2:    I can't get strcat to work.  I tried
  966.  
  967.         char *s1 = "Hello, ";
  968.         char *s2 = "world!";
  969.         char *s3 = strcat(s1, s2);
  970.  
  971.     but I got strange results.
  972.  
  973. A:    Again, the problem is that space for the concatenated result is
  974.     not properly allocated.  C does not provide an automatically-
  975.     managed string type.  C compilers only allocate memory for
  976.     objects explicitly mentioned in the source code (in the case of
  977.     "strings," this includes character arrays and string literals).
  978.     The programmer must arrange (explicitly) for sufficient space
  979.     for the results of run-time operations such as string
  980.     concatenation, typically by declaring arrays, or by calling
  981.     malloc.
  982.  
  983.     strcat performs no allocation; the second string is appended to
  984.     the first one, in place.  Therefore, one fix would be to declare
  985.     the first string as an array with sufficient space:
  986.  
  987.         char s1[20] = "Hello, ";
  988.  
  989.     Since strcat returns the value of its first argument (s1, in
  990.     this case), the s3 variable is superfluous.
  991.  
  992.     References: CT&P Sec. 3.2 p. 32.
  993.  
  994. 3.3:    But the man page for strcat says that it takes two char *'s as
  995.     arguments.  How am I supposed to know to allocate things?
  996.  
  997. A:    In general, when using pointers you _always_ have to consider
  998.     memory allocation, at least to make sure that the compiler is
  999.     doing it for you.  If a library routine's documentation does not
  1000.     explicitly mention allocation, it is usually the caller's
  1001.     problem.
  1002.  
  1003.     The Synopsis section at the top of a Unix-style man page can be
  1004.     misleading.  The code fragments presented there are closer to
  1005.     the function definition used by the call's implementor than the
  1006.     invocation used by the caller.  In particular, many routines
  1007.     which accept pointers (e.g. to structs or strings), are usually
  1008.     called with the address of some object (a struct, or an array --
  1009.     see questions 2.3 and 2.4.)  Another common example is stat().
  1010.  
  1011. 3.4:    I have a function that is supposed to return a string, but when
  1012.     it returns to its caller, the returned string is garbage.
  1013.  
  1014. A:    Make sure that the memory to which the function returns a
  1015.     pointer is correctly allocated.  The returned pointer should be
  1016.     to a statically-allocated buffer, or to a buffer passed in by
  1017.     the caller, but _not_ to a local (auto) array.  In other words,
  1018.     never do something like
  1019.  
  1020.         char *f()
  1021.         {
  1022.             char buf[10];
  1023.             /* ... */
  1024.             return buf;
  1025.         }
  1026.  
  1027.     One fix would to to declare the buffer as
  1028.  
  1029.             static char buf[10];
  1030.  
  1031.     See also question 17.5.
  1032.  
  1033. 3.5:    Why does some code carefully cast the values returned by malloc
  1034.     to the pointer type being allocated?
  1035.  
  1036. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  1037.     type, these casts were typically required to silence warnings
  1038.     about assignment between incompatible pointer types.
  1039.  
  1040. 3.6:    You can't use dynamically-allocated memory after you free it,
  1041.     can you?
  1042.  
  1043. A:    No.  Some early documentation for malloc stated that the
  1044.     contents of freed memory was "left undisturbed;" this ill-
  1045.     advised guarantee was never universal and is not required by
  1046.     ANSI.
  1047.  
  1048.     Few programmers would use the contents of freed memory
  1049.     deliberately, but it is easy to do so accidentally.  Consider
  1050.     the following (correct) code for freeing a singly-linked list:
  1051.  
  1052.         struct list *listp, *nextp;
  1053.         for(listp = base; listp != NULL; listp = nextp) {
  1054.             nextp = listp->next;
  1055.             free((char *)listp);
  1056.         }
  1057.  
  1058.     and notice what would happen if the more-obvious loop iteration
  1059.     expression listp = listp->next were used, without the temporary
  1060.     nextp pointer.
  1061.  
  1062.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1063.     p. 95.
  1064.  
  1065. 3.7:    How does free() know how many bytes to free?
  1066.  
  1067. A:    The malloc/free package remembers the size of each block it
  1068.     allocates and returns, so it is not necessary to remind it of
  1069.     the size when freeing.
  1070.  
  1071. 3.8:    So can I query the malloc package to find out how big an
  1072.     allocated block is?
  1073.  
  1074. A:    Not portably.
  1075.  
  1076. 3.9:    I'm allocating structures which contain pointers to other
  1077.     dynamically-allocated objects.  When I free a structure, do I
  1078.     have to free each subsidiary pointer first?
  1079.  
  1080. A:    Yes.  In general, you must arrange that each pointer returned
  1081.     from malloc be individually passed to free, exactly once (if it
  1082.     is freed at all).
  1083.  
  1084. 3.10:    I have a program which mallocs but then frees a lot of memory,
  1085.     but memory usage (as reported by ps) doesn't seem to go back
  1086.     down.
  1087.  
  1088. A:    Most implementations of malloc/free do not return freed memory
  1089.     to the operating system (if there is one), but merely make it
  1090.     available for future malloc calls.
  1091.  
  1092. 3.11:    Must I free allocated memory before the program exits?
  1093.  
  1094. A:    You shouldn't have to.  A real operating system definitively
  1095.     reclaims all memory when a program exits.  Nevertheless, some
  1096.     personal computers are said not to reliably recover memory, and
  1097.     all that can be inferred from the ANSI/ISO C Standard is that it
  1098.     is a "quality of implementation issue."
  1099.  
  1100.     References: ANSI Sec. 4.10.3.2 .
  1101.  
  1102. 3.12:    Is it legal to pass a null pointer as the first argument to
  1103.     realloc()?  Why would you want to?
  1104.  
  1105. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  1106.     which frees), but several earlier implementations do not support
  1107.     it, so it is not widely portable.  Passing an initially-null
  1108.     pointer to realloc can make it easier to write a self-starting
  1109.     incremental allocation algorithm.
  1110.  
  1111.     References: ANSI Sec. 4.10.3.4 .
  1112.  
  1113. 3.13:    What is the difference between calloc and malloc?  Is it safe to
  1114.     use calloc's zero-fill guarantee for pointer and floating-point
  1115.     values?  Does free work on memory allocated with calloc, or do
  1116.     you need a cfree?
  1117.  
  1118. A:    calloc(m, n) is essentially equivalent to
  1119.  
  1120.         p = malloc(m * n);
  1121.         memset(p, 0, m * n);
  1122.  
  1123.     The zero fill is all-bits-zero, and does not therefore guarantee
  1124.     useful zero values for pointers (see section 1 of this list) or
  1125.     floating-point values.  free can (and should) be used to free
  1126.     the memory allocated by calloc.
  1127.  
  1128.     References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1129.  
  1130. 3.14:    What is alloca and why is its use discouraged?
  1131.  
  1132. A:    alloca allocates memory which is automatically freed when the
  1133.     function which called alloca returns.  That is, memory allocated
  1134.     with alloca is local to a particular function's "stack frame" or
  1135.     context.
  1136.  
  1137.     alloca cannot be written portably, and is difficult to implement
  1138.     on machines without a stack.  Its use is problematical (and the
  1139.     obvious implementation on a stack-based machine fails) when its
  1140.     return value is passed directly to another function, as in
  1141.     fgets(alloca(100), 100, stdin).
  1142.  
  1143.     For these reasons, alloca cannot be used in programs which must
  1144.     be widely portable, no matter how useful it might be.
  1145.  
  1146.     References: ANSI Rationale Sec. 4.10.3 p. 102.
  1147.  
  1148.  
  1149. Section 4. Expressions
  1150.  
  1151. 4.1:    Why doesn't this code:
  1152.  
  1153.         a[i] = i++;
  1154.  
  1155.     work?
  1156.  
  1157. A:    The subexpression i++ causes a side effect -- it modifies i's
  1158.     value -- which leads to undefined behavior if i is also
  1159.     referenced elsewhere in the same expression.  (Note that
  1160.     although the language in K&R suggests that the behavior of this
  1161.     expression is unspecified, the ANSI/ISO C Standard makes the
  1162.     stronger statement that it is undefined -- see question 5.23.)
  1163.  
  1164.     References: ANSI Sec. 3.3 p. 39.
  1165.  
  1166. 4.2:    Under my compiler, the code
  1167.  
  1168.         int i = 7;
  1169.         printf("%d\n", i++ * i++);
  1170.  
  1171.     prints 49.  Regardless of the order of evaluation, shouldn't it
  1172.     print 56?
  1173.  
  1174. A:    Although the postincrement and postdecrement operators ++ and --
  1175.     perform the operations after yielding the former value, the
  1176.     implication of "after" is often misunderstood.  It is _not_
  1177.     guaranteed that the operation is performed immediately after
  1178.     giving up the previous value and before any other part of the
  1179.     expression is evaluated.  It is merely guaranteed that the
  1180.     update will be performed sometime before the expression is
  1181.     considered "finished" (before the next "sequence point," in ANSI
  1182.     C's terminology).  In the example, the compiler chose to
  1183.     multiply the previous value by itself and to perform both
  1184.     increments afterwards.
  1185.  
  1186.     The behavior of code which contains multiple, ambiguous side
  1187.     effects has always been undefined (see question 5.23).  Don't
  1188.     even try to find out how your compiler implements such things
  1189.     (contrary to the ill-advised exercises in many C textbooks); as
  1190.     K&R wisely point out, "if you don't know _how_ they are done on
  1191.     various machines, that innocence may help to protect you."
  1192.  
  1193.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  1194.     Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  1195.     (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  1196.  
  1197. 4.3:    I've experimented with the code
  1198.  
  1199.         int i = 2;
  1200.         i = i++;
  1201.  
  1202.     on several compilers.  Some gave i the value 2, some gave 3, but
  1203.     one gave 4.  I know the behavior is undefined, but how could it
  1204.     give 4?
  1205.  
  1206. A:    Undefined behavior means _anything_ can happen.  See question
  1207.     5.23.
  1208.  
  1209. 4.4:    People keep saying the behavior is undefined, but I just tried
  1210.     it on an ANSI-conforming compiler, and got the results I
  1211.     expected.
  1212.  
  1213. A:    A compiler may do anything it likes when faced with undefined
  1214.     behavior (and, within limits, with implementation-defined and
  1215.     unspecified behavior), including doing what you expect.  It's
  1216.     unwise to depend on it, though.  See also question 5.18.
  1217.  
  1218. 4.5:    Can I use explicit parentheses to force the order of evaluation
  1219.     I want?  Even if I don't, doesn't precedence dictate it?
  1220.  
  1221. A:    Operator precedence and explicit parentheses impose only a
  1222.     partial ordering on the evaluation of an expression.  Consider
  1223.     the expression
  1224.  
  1225.         f() + g() * h()
  1226.  
  1227.     -- although we know that the multiplication will happen before
  1228.     the addition, there is no telling which of the three functions
  1229.     will be called first.
  1230.  
  1231. 4.6:    But what about the &&, ||, and comma operators?
  1232.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  1233.  
  1234. A:    There is a special exception for those operators, (as well as
  1235.     ?: ); each of them does imply a sequence point (i.e. left-to-
  1236.     right evaluation is guaranteed).  Any book on C should make this
  1237.     clear.
  1238.  
  1239.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  1240.     K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  1241.     Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  1242.     CT&P Sec. 3.7 pp. 46-7.
  1243.  
  1244. 4.7:    If I'm not using the value of the expression, should I use i++
  1245.     or ++i to increment a variable?
  1246.  
  1247. A:    Since the two forms differ only in the value yielded, they are
  1248.     entirely equivalent when only their side effect is needed.
  1249.  
  1250. 4.8:    Why doesn't the code
  1251.  
  1252.         int a = 1000, b = 1000;
  1253.         long int c = a * b;
  1254.  
  1255.     work?
  1256.  
  1257. A:    Under C's integral promotion rules, the multiplication is
  1258.     carried out using int arithmetic, and the result may overflow
  1259.     and/or be truncated before being assigned to the long int left-
  1260.     hand-side.  Use an explicit cast to force long arithmetic:
  1261.  
  1262.         long int c = (long int)a * b;
  1263.  
  1264.  
  1265. Section 5. ANSI C
  1266.  
  1267. 5.1:    What is the "ANSI C Standard?"
  1268.  
  1269. A:    In 1983, the American National Standards Institute (ANSI)
  1270.     commissioned a committee, X3J11, to standardize the C language.
  1271.     After a long, arduous process, including several widespread
  1272.     public reviews, the committee's work was finally ratified as ANS
  1273.     X3.159-1989, on December 14, 1989, and published in the spring
  1274.     of 1990.  For the most part, ANSI C standardizes existing
  1275.     practice, with a few additions from C++ (most notably function
  1276.     prototypes) and support for multinational character sets
  1277.     (including the much-lambasted trigraph sequences).  The ANSI C
  1278.     standard also formalizes the C run-time library support
  1279.     routines.
  1280.  
  1281.     The published Standard includes a "Rationale," which explains
  1282.     many of its decisions, and discusses a number of subtle points,
  1283.     including several of those covered here.  (The Rationale is "not
  1284.     part of ANSI Standard X3.159-1989, but is included for
  1285.     information only.")
  1286.  
  1287.     The Standard has been adopted as an international standard,
  1288.     ISO/IEC 9899:1990, although the sections are numbered
  1289.     differently (briefly, ANSI sections 2 through 4 correspond
  1290.     roughly to ISO sections 5 through 7), and the Rationale is
  1291.     currently not included.
  1292.  
  1293. 5.2:    How can I get a copy of the Standard?
  1294.  
  1295. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  1296.     are available in the United States from
  1297.  
  1298.         American National Standards Institute
  1299.         11 W. 42nd St., 13th floor
  1300.         New York, NY  10036  USA
  1301.         (+1) 212 642 4900
  1302.  
  1303.     or
  1304.  
  1305.         Global Engineering Documents
  1306.         2805 McGaw Avenue
  1307.         Irvine, CA  92714  USA
  1308.         (+1) 714 261 1455
  1309.         (800) 854 7179  (U.S. & Canada)
  1310.  
  1311.     In other countries, contact the appropriate national standards
  1312.     body, or ISO in Geneva at:
  1313.  
  1314.         ISO Sales
  1315.         Case Postale 56
  1316.         CH-1211 Geneve 20
  1317.         Switzerland
  1318.  
  1319.     The cost is $130.00 from ANSI or $162.50 from Global.  Copies of
  1320.     the original X3.159 (including the Rationale) are still
  1321.     available at $205.00 from ANSI or $200.50 from Global.  Note
  1322.     that ANSI derives revenues to support its operations from the
  1323.     sale of printed standards, so electronic copies are _not_
  1324.     available.
  1325.  
  1326.     The mistitled _Annotated ANSI C Standard_, with annotations by
  1327.     Herbert Schildt, contains the full text of ISO 9899; it is
  1328.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  1329.     in the U.S. for approximately $40.  (It has been suggested that
  1330.     the price differential between this work and the official
  1331.     standard reflects the value of the annotations.)
  1332.  
  1333.     The text of the Rationale (not the full Standard) is now
  1334.     available for anonymous ftp from ftp.uu.net (see question 17.12)
  1335.     in directory doc/standards/ansi/X3.159-1989 .  The Rationale has
  1336.     also been printed by Silicon Press, ISBN 0-929306-07-4.
  1337.  
  1338. 5.3:    Does anyone have a tool for converting old-style C programs to
  1339.     ANSI C, or vice versa, or for automatically generating
  1340.     prototypes?
  1341.  
  1342. A:    Two programs, protoize and unprotoize, convert back and forth
  1343.     between prototyped and "old style" function definitions and
  1344.     declarations.  (These programs do _not_ handle full-blown
  1345.     translation between "Classic" C and ANSI C.)  These programs
  1346.     were once patches to the FSF GNU C compiler, gcc, but are now
  1347.     part of the main gcc distribution; look in pub/gnu at
  1348.     prep.ai.mit.edu (18.71.0.38), or at several other FSF archive
  1349.     sites.
  1350.  
  1351.     The unproto program (/pub/unix/unproto5.shar.Z on
  1352.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  1353.     and the next compiler pass, converting most of ANSI C to
  1354.     traditional C on-the-fly.
  1355.  
  1356.     The GNU GhostScript package comes with a little program called
  1357.     ansi2knr.
  1358.  
  1359.     Several prototype generators exist, many as modifications to
  1360.     lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  1361.     March, 1992.  There is another program called "cextract."  See
  1362.     also question 17.12.
  1363.  
  1364.     Finally, are you sure you really need to convert lots of old
  1365.     code to ANSI C?  The old-style function syntax is still
  1366.     acceptable.
  1367.  
  1368. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  1369.     # to insert the value of a symbolic constant into a message, but
  1370.     it keeps stringizing the macro's name rather than its value.
  1371.  
  1372. A:    You must use something like the following two-step procedure to
  1373.     force the macro to be expanded as well as stringized:
  1374.  
  1375.         #define str(x) #x
  1376.         #define xstr(x) str(x)
  1377.         #define OP plus
  1378.         char *opname = xstr(OP);
  1379.  
  1380.     This sets opname to "plus" rather than "OP".
  1381.  
  1382.     An equivalent circumlocution is necessary with the token-pasting
  1383.     operator ## when the values (rather than the names) of two
  1384.     macros are to be concatenated.
  1385.  
  1386.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  1387.  
  1388. 5.5:    I don't understand why I can't use const values in initializers
  1389.     and array dimensions, as in
  1390.  
  1391.         const int n = 5;
  1392.         int a[n];
  1393.  
  1394. A:    The const qualifier really means "read-only;" an object so
  1395.     qualified is a normal run-time object which cannot (normally) be
  1396.     assigned to.  The value of a const-qualified object is therefore
  1397.     _not_ a constant expression in the full sense of the term.  (C
  1398.     is unlike C++ in this regard.)  When you need a true compile-
  1399.     time constant, use a preprocessor #define.
  1400.  
  1401.     References: ANSI Sec. 3.4 .
  1402.  
  1403. 5.6:    What's the difference between "char const *p" and
  1404.     "char * const p"?
  1405.  
  1406. A:    "char const *p" is a pointer to a constant character (you can't
  1407.     change the character); "char * const p" is a constant pointer to
  1408.     a (variable) character (i.e. you can't change the pointer).
  1409.     (Read these "inside out" to understand them.  See question
  1410.     10.4.)
  1411.  
  1412.     References: ANSI Sec. 3.5.4.1 .
  1413.  
  1414. 5.7:    Why can't I pass a char ** to a function which expects a
  1415.     const char **?
  1416.  
  1417. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  1418.     const-T is expected, but the rule (an explicit exception) which
  1419.     permits slight mismatches in qualified pointer types is not
  1420.     applied recursively, but only at the top level.
  1421.  
  1422.     You must use explicit casts (e.g. (const char **) in this case)
  1423.     when assigning (or passing) pointers which have qualifier
  1424.     mismatches at other than the first level of indirection.
  1425.  
  1426.     References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
  1427.     Sec. 3.5.3 p. 65.
  1428.  
  1429. 5.8:    My ANSI compiler complains about a mismatch when it sees
  1430.  
  1431.         extern int func(float);
  1432.  
  1433.         int func(x)
  1434.         float x;
  1435.         {...
  1436.  
  1437. A:    You have mixed the new-style prototype declaration
  1438.     "extern int func(float);" with the old-style definition
  1439.     "int func(x) float x;".  It is usually safe to mix the two
  1440.     styles (see question 5.9), but not in this case.  Old C (and
  1441.     ANSI C, in the absence of prototypes, and in variable-length
  1442.     argument lists) "widens" certain arguments when they are passed
  1443.     to functions.  floats are promoted to double, and characters and
  1444.     short integers are promoted to ints.  (For old-style function
  1445.     definitions, the values are automatically converted back to the
  1446.     corresponding narrower types within the body of the called
  1447.     function, if they are declared that way there.)
  1448.  
  1449.     This problem can be fixed either by using new-style syntax
  1450.     consistently in the definition:
  1451.  
  1452.         int func(float x) { ... }
  1453.  
  1454.     or by changing the new-style prototype declaration to match the
  1455.     old-style definition:
  1456.  
  1457.         extern int func(double);
  1458.  
  1459.     (In this case, it would be clearest to change the old-style
  1460.     definition to use double as well, as long as the address of that
  1461.     parameter is not taken.)
  1462.  
  1463.     It may also be safer to avoid "narrow" (char, short int, and
  1464.     float) function arguments and return types.
  1465.  
  1466.     References: ANSI Sec. 3.3.2.2 .
  1467.  
  1468. 5.9:    Can you mix old-style and new-style function syntax?
  1469.  
  1470. A:    Doing so is perfectly legal, as long as you're careful (see
  1471.     especially question 5.8).  Note however that old-style syntax is
  1472.     marked as obsolescent, and support for it may be removed some
  1473.     day.
  1474.  
  1475.     References: ANSI Secs. 3.7.1, 3.9.5 .
  1476.  
  1477. 5.10:    Why does the declaration
  1478.  
  1479.         extern f(struct x {int s;} *p);
  1480.  
  1481.     give me an obscure warning message about "struct x introduced in
  1482.     prototype scope"?
  1483.  
  1484. A:    In a quirk of C's normal block scoping rules, a struct declared
  1485.     only within a prototype cannot be compatible with other structs
  1486.     declared in the same source file, nor can the struct tag be used
  1487.     later as you'd expect (it goes out of scope at the end of the
  1488.     prototype).
  1489.  
  1490.     To resolve the problem, precede the prototype with the vacuous-
  1491.     looking declaration
  1492.  
  1493.         struct x;
  1494.  
  1495.     , which will reserve a place at file scope for struct x's
  1496.     definition, which will be completed by the struct declaration
  1497.     within the prototype.
  1498.  
  1499.     References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
  1500.     Sec. 3.5.2.3 p. 63.
  1501.  
  1502. 5.11:    I'm getting strange syntax errors inside code which I've
  1503.     #ifdeffed out.
  1504.  
  1505. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  1506.     #ifndef must still consist of "valid preprocessing tokens."
  1507.     This means that there must be no unterminated comments or quotes
  1508.     (note particularly that an apostrophe within a contracted word
  1509.     could look like the beginning of a character constant), and no
  1510.     newlines inside quotes.  Therefore, natural-language comments
  1511.     and pseudocode should always be written between the "official"
  1512.     comment delimiters /* and */.  (But see also question 17.14, and
  1513.     6.7.)
  1514.  
  1515.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  1516.  
  1517. 5.12:    Can I declare main as void, to shut off these annoying "main
  1518.     returns no value" messages?  (I'm calling exit(), so main
  1519.     doesn't return.)
  1520.  
  1521. A:    No.  main must be declared as returning an int, and as taking
  1522.     either zero or two arguments (of the appropriate type).  If
  1523.     you're calling exit() but still getting warnings, you'll have to
  1524.     insert a redundant return statement (or use some kind of
  1525.     "notreached" directive, if available).
  1526.  
  1527.     Declaring a function as void does not merely silence warnings;
  1528.     it may also result in a different function call/return sequence,
  1529.     incompatible with what the caller (in main's case, the C run-
  1530.     time startup code) expects.
  1531.  
  1532.     References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  1533.  
  1534. 5.13:    Is exit(status) truly equivalent to returning status from main?
  1535.  
  1536. A:    Essentially, except under a few older, nonconforming systems,
  1537.     and unless data local to main might be needed during cleanup
  1538.     (due perhaps to a setbuf or atexit call).
  1539.  
  1540.     References: ANSI Sec. 2.1.2.2.3 p. 8.
  1541.  
  1542. 5.14:    Why does the ANSI Standard not guarantee more than six monocase
  1543.     characters of external identifier significance?
  1544.  
  1545. A:    The problem is older linkers which are neither under the control
  1546.     of the ANSI standard nor the C compiler developers on the
  1547.     systems which have them.  The limitation is only that
  1548.     identifiers be _significant_ in the first six characters, not
  1549.     that they be restricted to six characters in length.  This
  1550.     limitation is annoying, but certainly not unbearable, and is
  1551.     marked in the Standard as "obsolescent," i.e. a future revision
  1552.     will likely relax it.
  1553.  
  1554.     This concession to current, restrictive linkers really had to be
  1555.     made, no matter how vehemently some people oppose it.  (The
  1556.     Rationale notes that its retention was "most painful.")  If you
  1557.     disagree, or have thought of a trick by which a compiler
  1558.     burdened with a restrictive linker could present the C
  1559.     programmer with the appearance of more significance in external
  1560.     identifiers, read the excellently-worded section 3.1.2 in the
  1561.     X3.159 Rationale (see question 5.1), which discusses several
  1562.     such schemes and explains why they could not be mandated.
  1563.  
  1564.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  1565.     Sec. 3.1.2 pp. 19-21.
  1566.  
  1567. 5.15:    What is the difference between memcpy and memmove?
  1568.  
  1569. A:    memmove offers guaranteed behavior if the source and destination
  1570.     arguments overlap.  memcpy makes no such guarantee, and may
  1571.     therefore be more efficiently implementable.  When in doubt,
  1572.     it's safer to use memmove.
  1573.  
  1574.     References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1575.     Sec. 4.11.2 .
  1576.  
  1577. 5.16:    My compiler is rejecting the simplest possible test programs,
  1578.     with all kinds of syntax errors.
  1579.  
  1580. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  1581.     prototypes and the like.  See also questions 5.17 and 17.2.
  1582.  
  1583. 5.17:    Why are some ANSI/ISO Standard library routines showing up as
  1584.     undefined, even though I've got an ANSI compiler?
  1585.  
  1586. A:    It's not unusual to have a compiler available which accepts ANSI
  1587.     syntax, but not to have ANSI-compatible header files or run-time
  1588.     libraries installed.  See also questions 5.16 and 17.2.
  1589.  
  1590. 5.18:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  1591.     compliant, accept this code?  I know that the code is ANSI,
  1592.     because gcc accepts it.
  1593.  
  1594. A:    Most compilers support a few non-Standard extensions, gcc more
  1595.     so than most.  Are you sure that the code being rejected doesn't
  1596.     rely on such an extension?  It is usually a bad idea to perform
  1597.     experiments with a particular compiler to determine properties
  1598.     of a language; the applicable standard may permit variations, or
  1599.     the compiler may be wrong.  See also question 4.4.
  1600.  
  1601. 5.19:    Why can't I perform arithmetic on a void * pointer?
  1602.  
  1603. A:    The compiler doesn't know the size of the pointed-to objects.
  1604.     Before performing arithmetic, cast the pointer either to char *
  1605.     or to the type you're trying to manipulate.
  1606.  
  1607. 5.20:    Is char a[3] = "abc"; legal?  What does it mean?
  1608.  
  1609. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  1610.     though questionably useful.  It declares an array of size three,
  1611.     initialized with the three characters 'a', 'b', and 'c', without
  1612.     the usual terminating '\0' character; the array is therefore not
  1613.     a true C string and cannot be used with strcpy, printf %s, etc.
  1614.  
  1615.     References: ANSI Sec. 3.5.7 pp. 72-3.
  1616.  
  1617. 5.21:    What are #pragmas and what are they good for?
  1618.  
  1619. A:    The #pragma directive provides a single, well-defined "escape
  1620.     hatch" which can be used for all sorts of implementation-
  1621.     specific controls and extensions: source listing control,
  1622.     structure packing, warning suppression (like the old lint
  1623.     /* NOTREACHED */ comments), etc.
  1624.  
  1625.     References: ANSI Sec. 3.8.6 .
  1626.  
  1627. 5.22:    What does #pragma once mean?  I found it in some header files.
  1628.  
  1629. A:    It is an extension implemented by some preprocessors to help
  1630.     make header files idempotent; it is essentially equivalent to
  1631.     the #ifndef trick mentioned in question 6.4.
  1632.  
  1633. 5.23:    People seem to make a point of distinguishing between
  1634.     implementation-defined, unspecified, and undefined behavior.
  1635.     What's the difference?
  1636.  
  1637. A:    Briefly: implementation-defined means that an implementation
  1638.     must choose some behavior and document it.  Unspecified means
  1639.     that an implementation should choose some behavior, but need not
  1640.     document it.  Undefined means that absolutely anything might
  1641.     happen.  In no case does the Standard impose requirements; in
  1642.     the first two cases it occasionally suggests (and may require a
  1643.     choice from among) a small set of likely behaviors.
  1644.  
  1645.     If you're interested in writing portable code, you can ignore
  1646.     the distinctions, as you'll want to avoid code that depends on
  1647.     any of the three behaviors.
  1648.  
  1649.     References: ANSI Sec. 1.6, especially the Rationale.
  1650.  
  1651.  
  1652. Section 6. C Preprocessor
  1653.  
  1654. 6.1:    How can I write a generic macro to swap two values?
  1655.  
  1656. A:    There is no good answer to this question.  If the values are
  1657.     integers, a well-known trick using exclusive-OR could perhaps be
  1658.     used, but it will not work for floating-point values or
  1659.     pointers, or if the two values are the same variable (and the
  1660.     "obvious" supercompressed implementation for integral types
  1661.     a^=b^=a^=b is in fact illegal due to multiple side-effects; see
  1662.     questions 4.1 and 4.2).  If the macro is intended to be used on
  1663.     values of arbitrary type (the usual goal), it cannot use a
  1664.     temporary, since it does not know what type of temporary it
  1665.     needs, and standard C does not provide a typeof operator.
  1666.  
  1667.     The best all-around solution is probably to forget about using a
  1668.     macro, unless you're willing to pass in the type as a third
  1669.     argument.
  1670.  
  1671. 6.2:    I have some old code that tries to construct identifiers with a
  1672.     macro like
  1673.  
  1674.         #define Paste(a, b) a/**/b
  1675.  
  1676.     but it doesn't work any more.
  1677.  
  1678. A:    That comments disappeared entirely and could therefore be used
  1679.     for token pasting was an undocumented feature of some early
  1680.     preprocessor implementations, notably Reiser's.  ANSI affirms
  1681.     (as did K&R) that comments are replaced with white space.
  1682.     However, since the need for pasting tokens was demonstrated and
  1683.     real, ANSI introduced a well-defined token-pasting operator, ##,
  1684.     which can be used like this:
  1685.  
  1686.         #define Paste(a, b) a##b
  1687.  
  1688.     (See also question 5.4.)
  1689.  
  1690.     References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1691.  
  1692. 6.3:    What's the best way to write a multi-statement cpp macro?
  1693.  
  1694. A:    The usual goal is to write a macro that can be invoked as if it
  1695.     were a single function-call statement.  This means that the
  1696.     "caller" will be supplying the final semicolon, so the macro
  1697.     body should not.  The macro body cannot be a simple brace-
  1698.     delineated compound statement, because syntax errors would
  1699.     result if it were invoked (apparently as a single statement, but
  1700.     with a resultant extra semicolon) as the if branch of an if/else
  1701.     statement with an explicit else clause.
  1702.  
  1703.     The traditional solution is to use
  1704.  
  1705.         #define Func() do { \
  1706.             /* declarations */ \
  1707.             stmt1; \
  1708.             stmt2; \
  1709.             /* ... */ \
  1710.             } while(0)    /* (no trailing ; ) */
  1711.  
  1712.     When the "caller" appends a semicolon, this expansion becomes a
  1713.     single statement regardless of context.  (An optimizing compiler
  1714.     will remove any "dead" tests or branches on the constant
  1715.     condition 0, although lint may complain.)
  1716.  
  1717.     If all of the statements in the intended macro are simple
  1718.     expressions, with no declarations or loops, another technique is
  1719.     to write a single, parenthesized expression using one or more
  1720.     comma operators.  (See the example under question 6.10 below.
  1721.     This technique also allows a value to be "returned.")
  1722.  
  1723.     References: CT&P Sec. 6.3 pp. 82-3.
  1724.  
  1725. 6.4:    Is it acceptable for one header file to #include another?
  1726.  
  1727. A:    It's a question of style, and thus receives considerable debate.
  1728.     Many people believe that "nested #include files" are to be
  1729.     avoided: the prestigious Indian Hill Style Guide (see question
  1730.     14.3) disparages them; they can make it harder to find relevant
  1731.     definitions; they can lead to multiple-declaration errors if a
  1732.     file is #included twice; and they make manual Makefile
  1733.     maintenance very difficult.  On the other hand, they make it
  1734.     possible to use header files in a modular way (a header file
  1735.     #includes what it needs itself, rather than requiring each
  1736.     #includer to do so, a requirement that can lead to intractable
  1737.     headaches); a tool like grep (or a tags file) makes it easy to
  1738.     find definitions no matter where they are; a popular trick:
  1739.  
  1740.         #ifndef HEADERUSED
  1741.         #define HEADERUSED
  1742.         ...header file contents...
  1743.         #endif
  1744.  
  1745.     makes a header file "idempotent" so that it can safely be
  1746.     #included multiple times; and automated Makefile maintenance
  1747.     tools (which are a virtual necessity in large projects anyway)
  1748.     handle dependency generation in the face of nested #include
  1749.     files easily.  See also section 14.
  1750.  
  1751. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  1752.  
  1753. A:    No.  Preprocessing happens during an earlier pass of
  1754.     compilation, before type names have been parsed.  Consider using
  1755.     the predefined constants in ANSI's <limits.h>, if applicable, or
  1756.     a "configure" script, instead.  (Better yet, try to write code
  1757.     which is inherently insensitive to type sizes.)
  1758.  
  1759.     References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1760.     footnote 83.
  1761.  
  1762. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  1763.     is big-endian or little-endian?
  1764.  
  1765. A:    You probably can't.  (Preprocessor arithmetic uses only long
  1766.     ints, and there is no concept of addressing.)  Are you sure you
  1767.     need to know the machine's endianness explicitly?  Usually it's
  1768.     better to write code which doesn't care.
  1769.  
  1770. 6.7:    I've got this tricky processing I want to do at compile time and
  1771.     I can't figure out a way to get cpp to do it.
  1772.  
  1773. A:    cpp is not intended as a general-purpose preprocessor.  Rather
  1774.     than forcing it to do something inappropriate, consider writing
  1775.     your own little special-purpose preprocessing tool, instead.
  1776.     You can easily get a utility like make(1) to run it for you
  1777.     automatically.
  1778.  
  1779.     If you are trying to preprocess something other than C, consider
  1780.     using a general-purpose preprocessor (such as m4).
  1781.  
  1782. 6.8:    I inherited some code which contains far too many #ifdef's for
  1783.     my taste.  How can I preprocess the code to leave only one
  1784.     conditional compilation set, without running it through cpp and
  1785.     expanding all of the #include's and #define's as well?
  1786.  
  1787. A:    There are programs floating around called unifdef, rmifdef, and
  1788.     scpp which do exactly this.  (See question 17.12.)
  1789.  
  1790. 6.9:    How can I list all of the pre#defined identifiers?
  1791.  
  1792. A:    There's no standard way, although it is a frequent need.  The
  1793.     most expedient way is probably to extract printable strings from
  1794.     the compiler or preprocessor executable with something like the
  1795.     Unix strings(1) utility.
  1796.  
  1797. 6.10:    How can I write a cpp macro which takes a variable number of
  1798.     arguments?
  1799.  
  1800. A:    One popular trick is to define the macro with a single argument,
  1801.     and call it with a double set of parentheses, which appear to
  1802.     the preprocessor to indicate a single argument:
  1803.  
  1804.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  1805.  
  1806.         if(n != 0) DEBUG(("n is %d\n", n));
  1807.  
  1808.     The obvious disadvantage is that the caller must always remember
  1809.     to use the extra parentheses.  Other solutions are to use
  1810.     different macros (DEBUG1, DEBUG2, etc.) depending on the number
  1811.     of arguments, or to play games with commas:
  1812.  
  1813.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  1814.         #define _ ,
  1815.         DEBUG("i = %d" _ i)
  1816.  
  1817.     It is often better to use a bona-fide function, which can take a
  1818.     variable number of arguments in a well-defined way.  See
  1819.     questions 7.1 and 7.2.
  1820.  
  1821.  
  1822. Section 7. Variable-Length Argument Lists
  1823.  
  1824. 7.1:    How can I write a function that takes a variable number of
  1825.     arguments?
  1826.  
  1827. A:    Use the <stdarg.h> header (or, if you must, the older
  1828.     <varargs.h>).
  1829.  
  1830.     Here is a function which concatenates an arbitrary number of
  1831.     strings into malloc'ed memory:
  1832.  
  1833.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  1834.         #include <stdarg.h>        /* for va_ stuff */
  1835.         #include <string.h>        /* for strcat et al */
  1836.  
  1837.         char *vstrcat(char *first, ...)
  1838.         {
  1839.             size_t len = 0;
  1840.             char *retbuf;
  1841.             va_list argp;
  1842.             char *p;
  1843.  
  1844.             if(first == NULL)
  1845.                 return NULL;
  1846.  
  1847.             len = strlen(first);
  1848.  
  1849.             va_start(argp, first);
  1850.  
  1851.             while((p = va_arg(argp, char *)) != NULL)
  1852.                 len += strlen(p);
  1853.  
  1854.             va_end(argp);
  1855.  
  1856.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  1857.  
  1858.             if(retbuf == NULL)
  1859.                 return NULL;        /* error */
  1860.  
  1861.             (void)strcpy(retbuf, first);
  1862.  
  1863.             va_start(argp, first);
  1864.  
  1865.             while((p = va_arg(argp, char *)) != NULL)
  1866.                 (void)strcat(retbuf, p);
  1867.  
  1868.             va_end(argp);
  1869.  
  1870.             return retbuf;
  1871.         }
  1872.  
  1873.     Usage is something like
  1874.  
  1875.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1876.  
  1877.     Note the cast on the last argument.  (Also note that the caller
  1878.     must free the returned, malloc'ed storage.)
  1879.  
  1880.     Under a pre-ANSI compiler, rewrite the function definition
  1881.     without a prototype ("char *vstrcat(first) char *first; {"),
  1882.     include <stdio.h> rather than <stdlib.h>, add "extern
  1883.     char *malloc();", and use int instead of size_t.  You may also
  1884.     have to delete the (void) casts, and use the older varargs
  1885.     package instead of stdarg.  See the next question for hints.
  1886.  
  1887.     Remember that in variable-length argument lists, function
  1888.     prototypes do not supply parameter type information; therefore,
  1889.     default argument promotions apply (see question 5.8), and null
  1890.     pointer arguments must be typed explicitly (see question 1.2).
  1891.  
  1892.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1893.     Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1894.  
  1895. 7.2:    How can I write a function that takes a format string and a
  1896.     variable number of arguments, like printf, and passes them to
  1897.     printf to do most of the work?
  1898.  
  1899. A:    Use vprintf, vfprintf, or vsprintf.
  1900.  
  1901.     Here is an "error" routine which prints an error message,
  1902.     preceded by the string "error: " and terminated with a newline:
  1903.  
  1904.         #include <stdio.h>
  1905.         #include <stdarg.h>
  1906.  
  1907.         void
  1908.         error(char *fmt, ...)
  1909.         {
  1910.             va_list argp;
  1911.             fprintf(stderr, "error: ");
  1912.             va_start(argp, fmt);
  1913.             vfprintf(stderr, fmt, argp);
  1914.             va_end(argp);
  1915.             fprintf(stderr, "\n");
  1916.         }
  1917.  
  1918.     To use the older <varargs.h> package, instead of <stdarg.h>,
  1919.     change the function header to:
  1920.  
  1921.         void error(va_alist)
  1922.         va_dcl
  1923.         {
  1924.             char *fmt;
  1925.  
  1926.     change the va_start line to
  1927.  
  1928.         va_start(argp);
  1929.  
  1930.     and add the line
  1931.  
  1932.         fmt = va_arg(argp, char *);
  1933.  
  1934.     between the calls to va_start and vfprintf.  (Note that there is
  1935.     no semicolon after va_dcl.)
  1936.  
  1937.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1938.     Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1939.  
  1940. 7.3:    How can I discover how many arguments a function was actually
  1941.     called with?
  1942.  
  1943. A:    This information is not available to a portable program.  Some
  1944.     old systems provided a nonstandard nargs() function, but its use
  1945.     was always questionable, since it typically returned the number
  1946.     of words passed, not the number of arguments.  (Structures and
  1947.     floating point values are usually passed as several words.)
  1948.  
  1949.     Any function which takes a variable number of arguments must be
  1950.     able to determine from the arguments themselves how many of them
  1951.     there are.  printf-like functions do this by looking for
  1952.     formatting specifiers (%d and the like) in the format string
  1953.     (which is why these functions fail badly if the format string
  1954.     does not match the argument list).  Another common technique
  1955.     (useful when the arguments are all of the same type) is to use a
  1956.     sentinel value (often 0, -1, or an appropriately-cast null
  1957.     pointer) at the end of the list (see the execl and vstrcat
  1958.     examples under questions 1.2 and 7.1 above).
  1959.  
  1960. 7.4:    I can't get the va_arg macro to pull in an argument of type
  1961.     pointer-to-function.
  1962.  
  1963. A:    The type-rewriting games which the va_arg macro typically plays
  1964.     are stymied by overly-complicated types such as pointer-to-
  1965.     function.  If you use a typedef for the function pointer type,
  1966.     however, all will be well.
  1967.  
  1968.     References: ANSI Sec. 4.8.1.2 p. 124.
  1969.  
  1970. 7.5:    How can I write a function which takes a variable number of
  1971.     arguments and passes them to some other function (which takes a
  1972.     variable number of arguments)?
  1973.  
  1974. A:    In general, you cannot.  You must provide a version of that
  1975.     other function which accepts a va_list pointer, as does vfprintf
  1976.     in the example above.  If the arguments must be passed directly
  1977.     as actual arguments (not indirectly through a va_list pointer)
  1978.     to another function which is itself variadic (for which you do
  1979.     not have the option of creating an alternate, va_list-accepting
  1980.     version) no portable solution is possible.  (The problem can be
  1981.     solved by resorting to machine-specific assembly language.)
  1982.  
  1983. 7.6:    How can I call a function with an argument list built up at run
  1984.     time?
  1985.  
  1986. A:    There is no guaranteed or portable way to do this.  If you're
  1987.     curious, ask this list's editor, who has a few wacky ideas you
  1988.     could try...  (See also question 16.11.)
  1989.  
  1990.  
  1991. Section 8. Boolean Expressions and Variables
  1992.  
  1993. 8.1:    What is the right type to use for boolean values in C?  Why
  1994.     isn't it a standard type?  Should #defines or enums be used for
  1995.     the true and false values?
  1996.  
  1997. A:    C does not provide a standard boolean type, because picking one
  1998.     involves a space/time tradeoff which is best decided by the
  1999.     programmer.  (Using an int for a boolean may be faster, while
  2000.     using char may save data space.)
  2001.  
  2002.     The choice between #defines and enums is arbitrary and not
  2003.     terribly interesting (see also question 9.1).  Use any of
  2004.  
  2005.         #define TRUE  1            #define YES 1
  2006.         #define FALSE 0            #define NO  0
  2007.  
  2008.         enum bool {false, true};    enum bool {no, yes};
  2009.  
  2010.     or use raw 1 and 0, as long as you are consistent within one
  2011.     program or project.  (An enum may be preferable if your debugger
  2012.     expands enum values when examining variables.)
  2013.  
  2014.     Some people prefer variants like
  2015.  
  2016.         #define TRUE (1==1)
  2017.         #define FALSE (!TRUE)
  2018.  
  2019.     or define "helper" macros such as
  2020.  
  2021.         #define Istrue(e) ((e) != 0)
  2022.  
  2023.     These don't buy anything (see question 8.2 below; see also
  2024.     question 1.6).
  2025.  
  2026. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2027.     is considered "true" in C?  What if a built-in boolean or
  2028.     relational operator "returns" something other than 1?
  2029.  
  2030. A:    It is true (sic) that any nonzero value is considered true in C,
  2031.     but this applies only "on input", i.e. where a boolean value is
  2032.     expected.  When a boolean value is generated by a built-in
  2033.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2034.  
  2035.         if((a == b) == TRUE)
  2036.  
  2037.     will work as expected (as long as TRUE is 1), but it is
  2038.     obviously silly.  In general, explicit tests against TRUE and
  2039.     FALSE are undesirable, because some library functions (notably
  2040.     isupper, isalpha, etc.) return, on success, a nonzero value
  2041.     which is _not_ necessarily 1.  (Besides, if you believe that
  2042.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  2043.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  2044.     good rule of thumb is to use TRUE and FALSE (or the like) only
  2045.     for assignment to a Boolean variable, or as the return value
  2046.     from a Boolean function, never in a comparison.
  2047.  
  2048.     The preprocessor macros TRUE and FALSE are used for code
  2049.     readability, not because the underlying values might ever
  2050.     change.  (See also questions 1.7 and 1.9.)
  2051.  
  2052.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  2053.     Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  2054.     3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  2055.     Tortoise.
  2056.  
  2057.  
  2058. Section 9. Structs, Enums, and Unions
  2059.  
  2060. 9.1:    What is the difference between an enum and a series of
  2061.     preprocessor #defines?
  2062.  
  2063. A:    At the present time, there is little difference.  Although many
  2064.     people might have wished otherwise, the ANSI standard says that
  2065.     enumerations may be freely intermixed with integral types,
  2066.     without errors.  (If such intermixing were disallowed without
  2067.     explicit casts, judicious use of enums could catch certain
  2068.     programming errors.)
  2069.  
  2070.     Some advantages of enums are that the numeric values are
  2071.     automatically assigned, that a debugger may be able to display
  2072.     the symbolic values when enum variables are examined, and that
  2073.     they obey block scope.  (A compiler may also generate nonfatal
  2074.     warnings when enums and ints are indiscriminately mixed, since
  2075.     doing so can still be considered bad style even though it is not
  2076.     strictly illegal).  A disadvantage is that the programmer has
  2077.     little control over the size (or over those nonfatal warnings).
  2078.  
  2079.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  2080.     Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  2081.  
  2082. 9.2:    I heard that structures could be assigned to variables and
  2083.     passed to and from functions, but K&R I says not.
  2084.  
  2085. A:    What K&R I said was that the restrictions on struct operations
  2086.     would be lifted in a forthcoming version of the compiler, and in
  2087.     fact struct assignment and passing were fully functional in
  2088.     Ritchie's compiler even as K&R I was being published.  Although
  2089.     a few early C compilers lacked struct assignment, all modern
  2090.     compilers support it, and it is part of the ANSI C standard, so
  2091.     there should be no reluctance to use it.
  2092.  
  2093.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  2094.     Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  2095.  
  2096. 9.3:    How does struct passing and returning work?
  2097.  
  2098. A:    When structures are passed as arguments to functions, the entire
  2099.     struct is typically pushed on the stack, using as many words as
  2100.     are required.  (Programmers often choose to use pointers to
  2101.     structures instead, precisely to avoid this overhead.)
  2102.  
  2103.     Structures are often returned from functions in a location
  2104.     pointed to by an extra, compiler-supplied "hidden" argument to
  2105.     the function.  Some older compilers used a special, static
  2106.     location for structure returns, although this made struct-valued
  2107.     functions nonreentrant, which ANSI C disallows.
  2108.  
  2109.     References: ANSI Sec. 2.2.3 p. 13.
  2110.  
  2111. 9.4:    The following program works correctly, but it dumps core after
  2112.     it finishes.  Why?
  2113.  
  2114.         struct list
  2115.             {
  2116.             char *item;
  2117.             struct list *next;
  2118.             }
  2119.  
  2120.         /* Here is the main program. */
  2121.  
  2122.         main(argc, argv)
  2123.         ...
  2124.  
  2125. A:    A missing semicolon causes the compiler to believe that main
  2126.     returns a structure.  (The connection is hard to see because of
  2127.     the intervening comment.)  Since struct-valued functions are
  2128.     usually implemented by adding a hidden return pointer, the
  2129.     generated code for main() tries to accept three arguments,
  2130.     although only two are passed (in this case, by the C start-up
  2131.     code).  See also question 17.21.
  2132.  
  2133.     References: CT&P Sec. 2.3 pp. 21-2.
  2134.  
  2135. 9.5:    Why can't you compare structs?
  2136.  
  2137. A:    There is no reasonable way for a compiler to implement struct
  2138.     comparison which is consistent with C's low-level flavor.  A
  2139.     byte-by-byte comparison could be invalidated by random bits
  2140.     present in unused "holes" in the structure (such padding is used
  2141.     to keep the alignment of later fields correct; see questions
  2142.     9.10 and 9.11).  A field-by-field comparison would require
  2143.     unacceptable amounts of repetitive, in-line code for large
  2144.     structures.
  2145.  
  2146.     If you want to compare two structures, you must write your own
  2147.     function to do so.  C++ would let you arrange for the ==
  2148.     operator to map to your function.
  2149.  
  2150.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  2151.     Rationale Sec. 3.3.9 p. 47.
  2152.  
  2153. 9.6:    How can I read/write structs from/to data files?
  2154.  
  2155. A:    It is relatively straightforward to write a struct out using
  2156.     fwrite:
  2157.  
  2158.         fwrite((char *)&somestruct, sizeof(somestruct), 1, fp);
  2159.  
  2160.     and a corresponding fread invocation can read it back in.
  2161.     However, data files so written will _not_ be very portable (see
  2162.     questions 9.11 and 17.3).  Note also that on many systems you
  2163.     must use the "b" flag when fopening the files.
  2164.  
  2165. 9.7:    I came across some code that declared a structure like this:
  2166.  
  2167.         struct name
  2168.             {
  2169.             int namelen;
  2170.             char name[1];
  2171.             };
  2172.  
  2173.     and then did some tricky allocation to make the name array act
  2174.     like it had several elements.  Is this legal and/or portable?
  2175.  
  2176. A:    This technique is popular, although Dennis Ritchie has called it
  2177.     "unwarranted chumminess with the C implementation."  An ANSI
  2178.     Interpretation Ruling has deemed it (more precisely, access
  2179.     beyond the declared size of the name field) to be not strictly
  2180.     conforming, although a thorough treatment of the arguments
  2181.     surrounding the legality of the technique is beyond the scope of
  2182.     this list.  It seems, however, to be portable to all known
  2183.     implementations.  (Compilers which check array bounds carefully
  2184.     might issue warnings.)
  2185.  
  2186.     To be on the safe side, it may be preferable to declare the
  2187.     variable-size element very large, rather than very small; in the
  2188.     case of the above example:
  2189.  
  2190.         ...
  2191.         char name[MAXSIZE];
  2192.         ...
  2193.  
  2194.     where MAXSIZE is larger than any name which will be stored.
  2195.     (The trick so modified is said to be in conformance with the
  2196.     Standard.)
  2197.  
  2198.     References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  2199.  
  2200. 9.8:    How can I determine the byte offset of a field within a
  2201.     structure?
  2202.  
  2203. A:    ANSI C defines the offsetof macro, which should be used if
  2204.     available; see <stddef.h>.  If you don't have it, a suggested
  2205.     implementation is
  2206.  
  2207.         #define offsetof(type, mem) ((size_t) \
  2208.             ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  2209.  
  2210.     This implementation is not 100% portable; some compilers may
  2211.     legitimately refuse to accept it.
  2212.  
  2213.     See the next question for a usage hint.
  2214.  
  2215.     References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.
  2216.  
  2217. 9.9:    How can I access structure fields by name at run time?
  2218.  
  2219. A:    Build a table of names and offsets, using the offsetof() macro.
  2220.     The offset of field b in struct a is
  2221.  
  2222.         offsetb = offsetof(struct a, b)
  2223.  
  2224.     If structp is a pointer to an instance of this structure, and b
  2225.     is an int field with offset as computed above, b's value can be
  2226.     set indirectly with
  2227.  
  2228.         *(int *)((char *)structp + offsetb) = value;
  2229.  
  2230. 9.10:    Why does sizeof report a larger size than I expect for a
  2231.     structure type, as if there was padding at the end?
  2232.  
  2233. A:    Structures may have this padding (as well as internal padding;
  2234.     see also question 9.5), so that alignment properties will be
  2235.     preserved when an array of contiguous structures is allocated.
  2236.  
  2237. 9.11:    My compiler is leaving holes in structures, which is wasting
  2238.     space and preventing "binary" I/O to external data files.  Can I
  2239.     turn off the padding, or otherwise control the alignment of
  2240.     structs?
  2241.  
  2242. A:    Your compiler may provide an extension to give you this control
  2243.     (perhaps a #pragma), but there is no standard method.  See also
  2244.     question 17.3.
  2245.  
  2246. 9.12:    Can I initialize unions?
  2247.  
  2248. A:    ANSI Standard C allows an initializer for the first member of a
  2249.     union.  There is no standard way of initializing the other
  2250.     members (nor, under a pre-ANSI compiler, is there generally any
  2251.     way of initializing any of them).
  2252.  
  2253. 9.13:    How can I pass constant values to routines which accept struct
  2254.     arguments?
  2255.  
  2256. A:    C has no way of generating anonymous struct values.  You will
  2257.     have to use a temporary struct variable.
  2258.  
  2259.  
  2260. Section 10. Declarations
  2261.  
  2262. 10.1:    How do you decide which integer type to use?
  2263.  
  2264. A:    If you might need large values (above 32767 or below -32767),
  2265.     use long.  Otherwise, if space is very important (there are
  2266.     large arrays or many structures), use short.  Otherwise, use
  2267.     int.  If well-defined overflow characteristics are important
  2268.     and/or negative values are not, use the corresponding unsigned
  2269.     types.  (But beware of mixing signed and unsigned in
  2270.     expressions.)  Similar arguments apply when deciding between
  2271.     float and double.
  2272.  
  2273.     Although char or unsigned char can be used as a "tiny" int type,
  2274.     doing so is often more trouble than it's worth, due to
  2275.     unpredictable sign extension and increased code size.
  2276.  
  2277.     These rules obviously don't apply if the address of a variable
  2278.     is taken and must have a particular type.
  2279.  
  2280.     If for some reason you need to declare something with an _exact_
  2281.     size (usually the only good reason for doing so is when
  2282.     attempting to conform to some externally-imposed storage layout,
  2283.     but see question 17.3), be sure to encapsulate the choice behind
  2284.     an appropriate typedef.
  2285.  
  2286. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  2287.  
  2288. A:    Some vendors of C products for 64-bit machines support 64-bit
  2289.     long ints.  Others fear that too much existing code depends on
  2290.     sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
  2291.     bit long long (or __longlong) type instead.
  2292.  
  2293.     Programmers interested in writing portable code should therefore
  2294.     insulate their 64-bit type needs behind appropriate typedefs.
  2295.     Vendors who feel compelled to introduce a new, longer integral
  2296.     type should advertise it as being "at least 64 bits" (which is
  2297.     truly new; a type traditional C doesn't have), and not "exactly
  2298.     64 bits."
  2299.  
  2300. 10.3:    I can't seem to define a linked list successfully.  I tried
  2301.  
  2302.         typedef struct
  2303.             {
  2304.             char *item;
  2305.             NODEPTR next;
  2306.             } *NODEPTR;
  2307.  
  2308.     but the compiler gave me error messages.  Can't a struct in C
  2309.     contain a pointer to itself?
  2310.  
  2311. A:    Structs in C can certainly contain pointers to themselves; the
  2312.     discussion and example in section 6.5 of K&R make this clear.
  2313.     The problem with this example is that the NODEPTR typedef is not
  2314.     complete at the point where the "next" field is declared.  To
  2315.     fix it, first give the structure a tag ("struct node").  Then,
  2316.     declare the "next" field as "struct node *next;", and/or move
  2317.     the typedef declaration wholly before or wholly after the struct
  2318.     declaration.  One corrected version would be
  2319.  
  2320.         struct node
  2321.             {
  2322.             char *item;
  2323.             struct node *next;
  2324.             };
  2325.  
  2326.         typedef struct node *NODEPTR;
  2327.  
  2328.     , and there are at least three other equivalently correct ways
  2329.     of arranging it.
  2330.  
  2331.     A similar problem, with a similar solution, can arise when
  2332.     attempting to declare a pair of typedef'ed mutually referential
  2333.     structures.
  2334.  
  2335.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  2336.     Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  2337.  
  2338. 10.4:    How do I declare an array of N pointers to functions returning
  2339.     pointers to functions returning pointers to characters?
  2340.  
  2341. A:    This question can be answered in at least three ways:
  2342.  
  2343.     1.  char *(*(*a[N])())();
  2344.  
  2345.     2.  Build the declaration up in stages, using typedefs:
  2346.  
  2347.         typedef char *pc;    /* pointer to char */
  2348.         typedef pc fpc();    /* function returning pointer to char */
  2349.         typedef fpc *pfpc;    /* pointer to above */
  2350.         typedef pfpc fpfpc();    /* function returning... */
  2351.         typedef fpfpc *pfpfpc;    /* pointer to... */
  2352.         pfpfpc a[N];        /* array of... */
  2353.  
  2354.     3.  Use the cdecl program, which turns English into C and vice
  2355.         versa:
  2356.  
  2357.         cdecl> declare a as array of pointer to function returning
  2358.              pointer to function returning pointer to char
  2359.         char *(*(*a[])())()
  2360.  
  2361.         cdecl can also explain complicated declarations, help with
  2362.         casts, and indicate which set of parentheses the arguments
  2363.         go in (for complicated function definitions, like the
  2364.         above).  Versions of cdecl are in volume 14 of
  2365.         comp.sources.unix (see question 17.12) and K&R II.
  2366.  
  2367.     Any good book on C should explain how to read these complicated
  2368.     C declarations "inside out" to understand them ("declaration
  2369.     mimics use").
  2370.  
  2371.     References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  2372.  
  2373. 10.5:    I'm building a state machine with a bunch of functions, one for
  2374.     each state.  I want to implement state transitions by having
  2375.     each function return a pointer to the next state function.  I
  2376.     find a limitation in C's declaration mechanism: there's no way
  2377.     to declare these functions as returning a pointer to a function
  2378.     returning a pointer to a function returning a pointer to a
  2379.     function...
  2380.  
  2381. A:    You can't do it directly.  Either have the function return a
  2382.     generic function pointer type, and apply a cast before calling
  2383.     through it; or have it return a structure containing only a
  2384.     pointer to a function returning that structure.
  2385.  
  2386. 10.6:    My compiler is complaining about an invalid redeclaration of a
  2387.     function, but I only define it once and call it once.
  2388.  
  2389. A:    If the first call precedes the definition, the compiler will
  2390.     assume a function returns an int.  Non-int functions must be
  2391.     declared before they are called.
  2392.  
  2393.     References: K&R I Sec. 4.2 pp. 70; K&R II Sec. 4.2 p. 72; ANSI
  2394.     Sec. 3.3.2.2 .
  2395.  
  2396. 10.7:    What's the best way to declare and define global variables?
  2397.  
  2398. A:    First, though there can be many _declarations_ (and in many
  2399.     translation units) of a single "global" (strictly speaking,
  2400.     "external") variable (or function), there must be exactly one
  2401.     _definition_.  (The definition is the declaration that actually
  2402.     allocates space, and provides an initialization value, if any.)
  2403.     It is best to place the definition in some central (to the
  2404.     program, or to the module) .c file, with an external declaration
  2405.     in a header (".h") file, which is #included wherever the
  2406.     declaration is needed.  The .c file containing the definition
  2407.     should also #include the header file containing the external
  2408.     declaration, so that the compiler can check that the
  2409.     declarations match.
  2410.  
  2411.     This rule promotes a high degree of portability, and is
  2412.     consistent with the requirements of the ANSI C Standard.  Note
  2413.     that Unix compilers and linkers typically use a "common model"
  2414.     which allows multiple (uninitialized) definitions.  A few very
  2415.     odd systems may require an explicit initializer to distinguish a
  2416.     definition from an external declaration.
  2417.  
  2418.     It is possible to use preprocessor tricks to arrange that the
  2419.     declaration need only be typed once, in the header file, and
  2420.     "turned into" a definition, during exactly one #inclusion, via a
  2421.     special #define.
  2422.  
  2423.     References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  2424.     ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  2425.     Sec. F.5.11; H&S Sec. 4.8 pp. 79-80; CT&P Sec. 4.2 pp. 54-56.
  2426.  
  2427. 10.8:    What does extern mean in a function declaration?
  2428.  
  2429. A:    It can be used as a stylistic hint to indicate that the
  2430.     function's definition is probably in another source file, but
  2431.     there is no formal difference between
  2432.  
  2433.         extern int f();
  2434.     and
  2435.         int f();
  2436.  
  2437.     References: ANSI Sec. 3.1.2.2 .
  2438.  
  2439. 10.9:    I finally figured out the syntax for declaring pointers to
  2440.     functions, but now how do I initialize one?
  2441.  
  2442. A:    Use something like
  2443.  
  2444.         extern int func();
  2445.         int (*fp)() = func;
  2446.  
  2447.     When the name of a function appears in an expression but is not
  2448.     being called (i.e. is not followed by a "("), it "decays" into a
  2449.     pointer (i.e. it has its address implicitly taken), much as an
  2450.     array name does.
  2451.  
  2452.     An explicit extern declaration for the function is normally
  2453.     needed, since implicit external function declaration does not
  2454.     happen in this case (again, because the function name is not
  2455.     followed by a "(").
  2456.  
  2457. 10.10:    I've seen different methods used for calling through pointers to
  2458.     functions.  What's the story?
  2459.  
  2460. A:    Originally, a pointer to a function had to be "turned into" a
  2461.     "real" function, with the * operator (and an extra pair of
  2462.     parentheses, to keep the precedence straight), before calling:
  2463.  
  2464.         int r, func(), (*fp)() = func;
  2465.         r = (*fp)();
  2466.  
  2467.     It can also be argued that functions are always called through
  2468.     pointers, but that "real" functions decay implicitly into
  2469.     pointers (in expressions, as they do in initializations) and so
  2470.     cause no trouble.  This reasoning, made widespread through pcc
  2471.     and adopted in the ANSI standard, means that
  2472.  
  2473.         r = fp();
  2474.  
  2475.     is legal and works correctly, whether fp is a function or a
  2476.     pointer to one.  (The usage has always been unambiguous; there
  2477.     is nothing you ever could have done with a function pointer
  2478.     followed by an argument list except call through it.)  An
  2479.     explicit * is harmless, and still allowed (and recommended, if
  2480.     portability to older compilers is important).
  2481.  
  2482.     References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  2483.  
  2484. 10.11:    What's the auto keyword good for?
  2485.  
  2486. A:    Nothing; it's obsolete.
  2487.  
  2488.  
  2489. Section 11. Stdio
  2490.  
  2491. 11.1:    Why doesn't this code:
  2492.  
  2493.         char c;
  2494.         while((c = getchar()) != EOF)...
  2495.  
  2496.     work?
  2497.  
  2498. A:    For one thing, the variable to hold getchar's return value must
  2499.     be an int.  getchar can return all possible character values, as
  2500.     well as EOF.  By passing getchar's return value through a char,
  2501.     either a normal character might be misinterpreted as EOF, or the
  2502.     EOF might be altered and so never seen.
  2503.  
  2504.     References: CT&P Sec. 5.1 p. 70.
  2505.  
  2506. 11.2:    Why doesn't the code scanf("%d", i); work?
  2507.  
  2508. A:    scanf needs pointers to the variables it is to fill in; you must
  2509.     call scanf("%d", &i);
  2510.  
  2511. 11.3:    Why doesn't this code:
  2512.  
  2513.         double d;
  2514.         scanf("%f", &d);
  2515.  
  2516.     work?
  2517.  
  2518. A:    scanf uses %lf for values of type double, and %f for float.
  2519.     (Note the discrepancy with printf, which uses %f for both double
  2520.     and float, due to C's default argument promotion rules.)
  2521.  
  2522. 11.4:    Why won't the code
  2523.  
  2524.         while(!feof(infp)) {
  2525.             fgets(buf, MAXLINE, infp);
  2526.             fputs(buf, outfp);
  2527.         }
  2528.  
  2529.     work?
  2530.  
  2531. A:    C's I/O is not like Pascal's.  EOF is only indicated _after_ an
  2532.     input routine has tried to read, and has reached end-of-file.
  2533.     Usually, you should just check the return value of the input
  2534.     routine (fgets in this case); often, you don't need to use
  2535.     feof() at all.
  2536.  
  2537. 11.5:    Why does everyone say not to use gets()?
  2538.  
  2539. A:    It cannot be told the size of the buffer it's to read into, so
  2540.     it cannot be prevented from overflowing that buffer.  See
  2541.     question 3.1 for a code fragment illustrating the replacement of
  2542.     gets() with fgets().
  2543.  
  2544. 11.6:    Why does errno contain ENOTTY after a call to printf?
  2545.  
  2546. A:    Many implementations of the stdio package adjust their behavior
  2547.     slightly if stdout is a terminal.  To make the determination,
  2548.     these implementations perform an operation which fails (with
  2549.     ENOTTY) if stdout is not a terminal.  Although the output
  2550.     operation goes on to complete successfully, errno still contains
  2551.     ENOTTY.
  2552.  
  2553.     References: CT&P Sec. 5.4 p. 73.
  2554.  
  2555. 11.7:    My program's prompts and intermediate output don't always show
  2556.     up on the screen, especially when I pipe the output through
  2557.     another program.
  2558.  
  2559. A:    It is best to use an explicit fflush(stdout) whenever output
  2560.     should definitely be visible.  Several mechanisms attempt to
  2561.     perform the fflush for you, at the "right time," but they tend
  2562.     to apply only when stdout is a terminal.  (See question 11.6.)
  2563.  
  2564. 11.8:    When I read from the keyboard with scanf, it seems to hang until
  2565.     I type one extra line of input.
  2566.  
  2567. A:    scanf was designed for free-format input, which is seldom what
  2568.     you want when reading from the keyboard.  In particular, "\n" in
  2569.     a format string does _not_ mean to expect a newline, but rather
  2570.     to read and discard characters as long as each is a whitespace
  2571.     character.
  2572.  
  2573.     A related problem is that unexpected non-numeric input can cause
  2574.     scanf to "jam."  Because of these problems, it is usually better
  2575.     to use fgets to read a whole line, and then use sscanf or other
  2576.     string functions to pick apart the line buffer.  If you do use
  2577.     sscanf, don't forget to check the return value to make sure that
  2578.     the expected number of items were found.
  2579.  
  2580. 11.9:    I'm trying to update a file in place, by using fopen mode "r+",
  2581.     then reading a certain string, and finally writing back a
  2582.     modified string, but it's not working.
  2583.  
  2584. A:    Be sure to call fseek before you write, both to seek back to the
  2585.     beginning of the string you're trying to overwrite, and because
  2586.     an fseek or fflush is always required between reading and
  2587.     writing in the read/write "+" modes.
  2588.  
  2589.     References: ANSI Sec. 4.9.5.3 p. 131.
  2590.  
  2591. 11.10:    How can I read one character at a time, without waiting for the
  2592.     RETURN key?
  2593.  
  2594. A:    See question 16.1.
  2595.  
  2596. 11.11:    How can I flush pending input so that a user's typeahead isn't
  2597.     read at the next prompt?  Will fflush(stdin) work?
  2598.  
  2599. A:    fflush is defined only for output streams.  Since its definition
  2600.     of "flush" is to complete the writing of buffered characters
  2601.     (not to discard them), discarding unread input would not be an
  2602.     analogous meaning for fflush on input streams.  There is no
  2603.     standard way to discard unread characters from a stdio input
  2604.     buffer, nor would such a way be sufficient; unread characters
  2605.     can also accumulate in other, OS-level input buffers.
  2606.  
  2607. 11.12:    How can I redirect stdin or stdout to a file from within a
  2608.     program?
  2609.  
  2610. A:    Use freopen.
  2611.  
  2612. 11.13:    Once I've used freopen, how can I get the original stdout (or
  2613.     stdin) back?
  2614.  
  2615. A:    If you need to switch back and forth, the best all-around
  2616.     solution is not to use freopen in the first place.  Try using
  2617.     your own explicit output (or input) stream variable, which you
  2618.     can reassign at will, while leaving the original stdout (or
  2619.     stdin) undisturbed.
  2620.  
  2621. 11.14:    How can I recover the file name given an open file descriptor?
  2622.  
  2623. A:    This problem is, in general, insoluble.  Under Unix, for
  2624.     instance, a scan of the entire disk, (perhaps requiring special
  2625.     permissions) would theoretically be required, and would fail if
  2626.     the file descriptor was a pipe or referred to a deleted file
  2627.     (and could give a misleading answer for a file with multiple
  2628.     links).  It is best to remember the names of files yourself when
  2629.     you open them (perhaps with a wrapper function around fopen).
  2630.  
  2631.  
  2632. Section 12. Library Subroutines
  2633.  
  2634. 12.1:    Why does strncpy not always place a '\0' termination in the
  2635.     destination string?
  2636.  
  2637. A:    strncpy was first designed to handle a now-obsolete data
  2638.     structure, the fixed-length, not-necessarily-\0-terminated
  2639.     "string."  strncpy is admittedly a bit cumbersome to use in
  2640.     other contexts, since you must often append a '\0' to the
  2641.     destination string by hand.
  2642.  
  2643. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  2644.     as the comparison function, but it's not working.
  2645.  
  2646. A:    By "array of strings" you probably mean "array of pointers to
  2647.     char."  The arguments to qsort's comparison function are
  2648.     pointers to the objects being sorted, in this case, pointers to
  2649.     pointers to char.  (strcmp, of course, accepts simple pointers
  2650.     to char.)
  2651.  
  2652.     The comparison routine's arguments are expressed as "generic
  2653.     pointers," const void * or char *.  They must be converted back
  2654.     to what they "really are" (char **) and dereferenced, yielding
  2655.     char *'s which can be usefully compared.  Write a comparison
  2656.     function like this:
  2657.  
  2658.         int pstrcmp(p1, p2)    /* compare strings through pointers */
  2659.         char *p1, *p2;        /* const void * for ANSI C */
  2660.         {
  2661.             return strcmp(*(char **)p1, *(char **)p2);
  2662.         }
  2663.  
  2664.     Beware of the discussion in K&R II Sec. 5.11 pp. 119-20, which
  2665.     is not discussing Standard library qsort.
  2666.  
  2667. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  2668.     comparison routine takes pointers to structures, but the
  2669.     compiler complains that the function is of the wrong type for
  2670.     qsort.  How can I cast the function pointer to shut off the
  2671.     warning?
  2672.  
  2673. A:    The conversions must be in the comparison function, which must
  2674.     be declared as accepting "generic pointers" (const void * or
  2675.     char *) as discussed in question 12.2 above.  The code might
  2676.     look like
  2677.  
  2678.         int mystructcmp(p1, p2)
  2679.         char *p1, *p2;        /* const void * for ANSI C */
  2680.         {
  2681.             struct mystruct *sp1 = (struct mystruct *)p1;
  2682.             struct mystruct *sp2 = (struct mystruct *)p2;
  2683.             /* now compare sp1->whatever and *sp2-> ... */
  2684.         }
  2685.  
  2686.     (If, on the other hand, you're sorting pointers to structures,
  2687.     you'll need indirection, as in question 12.2:
  2688.     sp1 = *(struct mystruct **)p1 .)
  2689.  
  2690. 12.4:    How can I convert numbers to strings (the opposite of atoi)?  Is
  2691.     there an itoa function?
  2692.  
  2693. A:    Just use sprintf.  (You'll have to allocate space for the result
  2694.     somewhere anyway; see questions 3.1 and 3.2.  Don't worry that
  2695.     sprintf may be overkill, potentially wasting run time or code
  2696.     space; it works well in practice.)
  2697.  
  2698.     References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2699.  
  2700. 12.5:    How can I get the current date or time of day in a C program?
  2701.  
  2702. A:    Just use the time, ctime, and/or localtime functions.  (These
  2703.     routines have been around for years, and are in the ANSI
  2704.     standard.)  Here is a simple example:
  2705.  
  2706.         #include <stdio.h>
  2707.         #include <time.h>
  2708.  
  2709.         main()
  2710.         {
  2711.             time_t now = time((time_t *)NULL);
  2712.             printf("It's %.24s.\n", ctime(&now));
  2713.             return 0;
  2714.         }
  2715.  
  2716.     References: ANSI Sec. 4.12 .
  2717.  
  2718. 12.6:    I know that the library routine localtime will convert a time_t
  2719.     into a broken-down struct tm, and that ctime will convert a
  2720.     time_t to a printable string.  How can I perform the inverse
  2721.     operations of converting a struct tm or a string into a time_t?
  2722.  
  2723. A:    ANSI C specifies a library routine, mktime, which converts a
  2724.     struct tm to a time_t.  Several public-domain versions of this
  2725.     routine are available in case your compiler does not support it
  2726.     yet.
  2727.  
  2728.     Converting a string to a time_t is harder, because of the wide
  2729.     variety of date and time formats which should be parsed.  Some
  2730.     systems provide a strptime function; another popular routine is
  2731.     partime (widely distributed with the RCS package), but these are
  2732.     less likely to become standardized.
  2733.  
  2734.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2735.     Sec. 4.12.2.3 .
  2736.  
  2737. 12.7:    How can I add n days to a date?  How can I find the difference
  2738.     between two dates?
  2739.  
  2740. A:    The ANSI/ISO Standard C mktime and difftime functions provide
  2741.     support for both problems.  mktime accepts non-normalized dates,
  2742.     so it is straightforward to take a filled in struct tm, add or
  2743.     subtract from the tm_mday field, and call mktime to normalize
  2744.     the year, month, and day fields (and convert to a time_t value).
  2745.     difftime computes the difference, in seconds, between two time_t
  2746.     values; mktime can be used to compute time_t values for two
  2747.     dates to be subtracted.  (Note, however, that these solutions
  2748.     only work for dates which can be represented as time_t's.)  See
  2749.     also questions 12.6 and 17.28.
  2750.  
  2751.     References: K&R II Sec. B10 p. 256; H&S Secs. 20.4, 20.5
  2752.     pp. 361-362; ANSI Secs. 4.12.2.2, 4.12.2.3 .
  2753.  
  2754. 12.8:    I need a random number generator.
  2755.  
  2756. A:    The standard C library has one: rand().  The implementation on
  2757.     your system may not be perfect, but writing a better one isn't
  2758.     necessarily easy, either.
  2759.  
  2760.     References: ANSI Sec. 4.10.2.1 p. 154; Knuth Vol. 2 Chap. 3
  2761.     pp. 1-177.
  2762.  
  2763. 12.9:    How can I get random integers in a certain range?
  2764.  
  2765. A:    The obvious way,
  2766.  
  2767.         rand() % N
  2768.  
  2769.     (where N is of course the range) is poor, because the low-order
  2770.     bits of many random number generators are distressingly non-
  2771.     random.  (See question 12.11.)  A better method is something
  2772.     like
  2773.  
  2774.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  2775.  
  2776.     If you're worried about using floating point, you could try
  2777.  
  2778.         rand() / (RAND_MAX / N + 1)
  2779.  
  2780.     Both methods obviously require knowing RAND_MAX (which ANSI
  2781.     defines in <stdlib.h>), and assume that N is much less than
  2782.     RAND_MAX.
  2783.  
  2784. 12.10:    Each time I run my program, I get the same sequence of numbers
  2785.     back from rand().
  2786.  
  2787. A:    You can call srand() to seed the pseudo-random number generator
  2788.     with a more random initial value.  Popular seed values are the
  2789.     time of day, or the elapsed time before the user presses a key
  2790.     (although keypress times are hard to determine portably; see
  2791.     question 16.10).
  2792.  
  2793.     References: ANSI Sec. 4.10.2.2 p. 154.
  2794.  
  2795. 12.11:    I need a random true/false value, so I'm taking rand() % 2, but
  2796.     it's just alternating 0, 1, 0, 1, 0...
  2797.  
  2798. A:    Poor pseudorandom number generators (such as the ones
  2799.     unfortunately supplied with some systems) are not very random in
  2800.     the low-order bits.  Try using the higher-order bits.  See
  2801.     question 12.9.
  2802.  
  2803. 12.12:    I'm trying to port this        A:  These routines are variously
  2804.     old program.  Why do I            obsolete; you should
  2805.     get "undefined external"        instead:
  2806.     errors for:
  2807.  
  2808.     index?                    use strchr.
  2809.     rindex?                    use strrchr.
  2810.     bcopy?                    use memmove, after
  2811.                         interchanging the first and
  2812.                         second arguments (see also
  2813.                         question 5.15).
  2814.     bcmp?                    use memcmp.
  2815.     bzero?                    use memset, with a second
  2816.                         argument of 0.
  2817.  
  2818. 12.13:    I keep getting errors due to library routines being undefined,
  2819.     but I'm #including all the right header files.
  2820.  
  2821. A:    In some cases (especially if the routines are nonstandard) you
  2822.     may have to explicitly ask for the correct libraries to be
  2823.     searched when you link the program.  See also question 15.2.
  2824.  
  2825. 12.14:    I'm still getting errors due to library routines being
  2826.     undefined, even though I'm using -l to request the libraries
  2827.     while linking.
  2828.  
  2829. A:    Many linkers make one pass over the list of object files and
  2830.     libraries you specify, and extract from libraries only those
  2831.     modules which satisfy references which have so far come up as
  2832.     undefined.  Therefore, the order in which libraries are listed
  2833.     with respect to object files (and each other) is significant;
  2834.     usually, you want to search the libraries last (i.e., under
  2835.     Unix, put any -l switches towards the end of the command line).
  2836.  
  2837. 12.15:    I need some code to do regular expression matching.
  2838.  
  2839. A:    Look for the regexp library (supplied with many Unix systems),
  2840.     or get Henry Spencer's regexp package from cs.toronto.edu in
  2841.     pub/regexp.shar.Z (see also question 17.12).
  2842.  
  2843. 12.16:    How can I split up a command line into argc and argv, like the
  2844.     shell does?
  2845.  
  2846. A:    Most systems have a routine called strtok.
  2847.  
  2848.     References: ANSI Sec. 4.11.5.8; K&R II Sec. B3 p. 250; H&S
  2849.     Sec. 15.7; PCS p. 178.
  2850.  
  2851.  
  2852. Section 13. Lint
  2853.  
  2854. 13.1:    I just typed in this program, and it's acting strangely.  Can
  2855.     you see anything wrong with it?
  2856.  
  2857. A:    Try running lint first (perhaps with the -a, -c, -h, -p and/or
  2858.     other options).  Many C compilers are really only half-
  2859.     compilers, electing not to diagnose numerous source code
  2860.     difficulties which would not actively preclude code generation.
  2861.  
  2862. 13.2:    How can I shut off the "warning: possible pointer alignment
  2863.     problem" message lint gives me for each call to malloc?
  2864.  
  2865. A:    The problem is that traditional versions of lint do not know,
  2866.     and cannot be told, that malloc "returns a pointer to space
  2867.     suitably aligned for storage of any type of object."  It is
  2868.     possible to provide a pseudoimplementation of malloc, using a
  2869.     #define inside of #ifdef lint, which effectively shuts this
  2870.     warning off, but a simpleminded #definition will also suppress
  2871.     meaningful messages about truly incorrect invocations.  It may
  2872.     be easier simply to ignore the message, perhaps in an automated
  2873.     way with grep -v.
  2874.  
  2875. 13.3:    Where can I get an ANSI-compatible lint?
  2876.  
  2877. A:    A product called FlexeLint is available (in "shrouded source
  2878.     form," for compilation on 'most any system) from
  2879.  
  2880.         Gimpel Software
  2881.         3207 Hogarth Lane
  2882.         Collegeville, PA  19426  USA
  2883.         (+1) 215 584 4261
  2884.  
  2885.     The System V release 4 lint is ANSI-compatible, and is available
  2886.     separately (bundled with other C tools) from UNIX Support Labs
  2887.     (a subsidiary of AT&T), or from System V resellers.
  2888.  
  2889.  
  2890. Section 14. Style
  2891.  
  2892. 14.1:    Here's a neat trick:
  2893.  
  2894.         if(!strcmp(s1, s2))
  2895.  
  2896.     Is this good style?
  2897.  
  2898. A:    It is not particularly good style, although it is a popular
  2899.     idiom.  The test succeeds if the two strings are equal, but its
  2900.     form suggests that it tests for inequality.
  2901.  
  2902.     Another solution is to use a macro:
  2903.  
  2904.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2905.  
  2906.     Opinions on code style, like those on religion, can be debated
  2907.     endlessly.  Though good style is a worthy goal, and can usually
  2908.     be recognized, it cannot be codified.
  2909.  
  2910. 14.2:    What's the best style for code layout in C?
  2911.  
  2912. A:    K&R, while providing the example most often copied, also supply
  2913.     a good excuse for avoiding it:
  2914.  
  2915.         The position of braces is less important,
  2916.         although people hold passionate beliefs.  We
  2917.         have chosen one of several popular styles.  Pick
  2918.         a style that suits you, then use it
  2919.         consistently.
  2920.  
  2921.     It is more important that the layout chosen be consistent (with
  2922.     itself, and with nearby or common code) than that it be
  2923.     "perfect."  If your coding environment (i.e. local custom or
  2924.     company policy) does not suggest a style, and you don't feel
  2925.     like inventing your own, just copy K&R.  (The tradeoffs between
  2926.     various indenting and brace placement options can be
  2927.     exhaustively and minutely examined, but don't warrant repetition
  2928.     here.  See also the Indian Hill Style Guide.)
  2929.  
  2930.     The elusive quality of "good style" involves much more than mere
  2931.     code layout details; don't spend time on formatting to the
  2932.     exclusion of more substantive code quality issues.
  2933.  
  2934.     References: K&R Sec. 1.2 p. 10.
  2935.  
  2936. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  2937.     standards?
  2938.  
  2939. A:    Various documents are available for anonymous ftp from:
  2940.  
  2941.         Site:            File or directory:
  2942.  
  2943.         cs.washington.edu    ~ftp/pub/cstyle.tar.Z
  2944.         (128.95.1.4)        (the updated Indian Hill guide)
  2945.  
  2946.         cs.toronto.edu        doc/programming
  2947.  
  2948.         giza.cis.ohio-state.edu    pub/style-guide
  2949.  
  2950.  
  2951. Section 15. Floating Point
  2952.  
  2953. 15.1:    My floating-point calculations are acting strangely and giving
  2954.     me different answers on different machines.
  2955.  
  2956. A:    First, make sure that you have #included <math.h>, and correctly
  2957.     declared other functions returning double.
  2958.  
  2959.     If the problem isn't that simple, recall that most digital
  2960.     computers use floating-point formats which provide a close but
  2961.     by no means exact simulation of real number arithmetic.
  2962.     Underflow, cumulative precision loss, and other anomalies are
  2963.     often troublesome.
  2964.  
  2965.     Don't assume that floating-point results will be exact, and
  2966.     especially don't assume that floating-point values can be
  2967.     compared for equality.  (Don't throw haphazard "fuzz factors"
  2968.     in, either.)
  2969.  
  2970.     These problems are no worse for C than they are for any other
  2971.     computer language.  Floating-point semantics are usually defined
  2972.     as "however the processor does them;" otherwise a compiler for a
  2973.     machine without the "right" model would have to do prohibitively
  2974.     expensive emulations.
  2975.  
  2976.     This article cannot begin to list the pitfalls associated with,
  2977.     and workarounds appropriate for, floating-point work.  A good
  2978.     programming text should cover the basics.
  2979.  
  2980.     References: EoPS Sec. 6 pp. 115-8.
  2981.  
  2982. 15.2:    I'm trying to do some simple trig, and I am #including <math.h>,
  2983.     but I keep getting "undefined: _sin" compilation errors.
  2984.  
  2985. A:    Make sure you're linking with the correct math library.  For
  2986.     instance, under Unix, you usually need to use the -lm option,
  2987.     and at the _end_ of the command line, when compiling/linking.
  2988.     See also question 12.14.
  2989.  
  2990. 15.3:    Why doesn't C have an exponentiation operator?
  2991.  
  2992. A:    Because few processors have an exponentiation instruction.
  2993.     Instead, you can #include <math.h> and use the pow() function,
  2994.     although explicit multiplication is often better for small
  2995.     positive integral exponents.
  2996.  
  2997.     References: ANSI Sec. 4.5.5.1 .
  2998.  
  2999. 15.4:    How do I round numbers?
  3000.  
  3001. A:    The simplest and most straightforward way is with code like
  3002.  
  3003.         (int)(x + 0.5)
  3004.  
  3005.     This won't work properly for negative numbers, though.
  3006.  
  3007. 15.5:    How do I test for IEEE NaN and other special values?
  3008.  
  3009. A:    Many systems with high-quality IEEE floating-point
  3010.     implementations provide facilities (e.g. an isnan() macro) to
  3011.     deal with these values cleanly, and the Numerical C Extensions
  3012.     Group (NCEG) is working to formally standardize such facilities.
  3013.     A crude but usually effective test for NaN is exemplified by
  3014.  
  3015.         #define isnan(x) ((x) != (x))
  3016.  
  3017.     although non-IEEE-aware compilers may optimize the test away.
  3018.  
  3019. 15.6:    I'm having trouble with a Turbo C program which crashes and says
  3020.     something like "floating point formats not linked."
  3021.  
  3022. A:    Some compilers for small machines, including Turbo C (and
  3023.     Ritchie's original PDP-11 compiler), leave out floating point
  3024.     support if it looks like it will not be needed.  In particular,
  3025.     the non-floating-point versions of printf and scanf save space
  3026.     by not including code to handle %e, %f, and %g.  It happens that
  3027.     Turbo C's heuristics for determining whether the program uses
  3028.     floating point are insufficient, and the programmer must
  3029.     sometimes insert an extra, explicit call to a floating-point
  3030.     library routine to force loading of floating-point support.
  3031.  
  3032.  
  3033. Section 16. System Dependencies
  3034.  
  3035. 16.1:    How can I read a single character from the keyboard without
  3036.     waiting for a newline?
  3037.  
  3038. A:    Contrary to popular belief and many people's wishes, this is not
  3039.     a C-related question.  (Nor are closely-related questions
  3040.     concerning the echo of keyboard input.)  The delivery of
  3041.     characters from a "keyboard" to a C program is a function of the
  3042.     operating system in use, and has not been standardized by the C
  3043.     language.  Some versions of curses have a cbreak() function
  3044.     which does what you want.  If you're specifically trying to read
  3045.     a short password without echo, you might try getpass().  Under
  3046.     Unix, use ioctl to play with the terminal driver modes (CBREAK
  3047.     or RAW under "classic" versions; ICANON, c_cc[VMIN] and
  3048.     c_cc[VTIME] under System V or Posix systems).  Under MS-DOS, use
  3049.     getch().  Under VMS, try the Screen Management (SMG$) routines,
  3050.     or curses, or issue low-level $QIO's with the IO$_READVBLK (and
  3051.     perhaps IO$M_NOECHO) function codes to ask for one character at
  3052.     a time.  Under other operating systems, you're on your own.
  3053.     Beware that some operating systems make this sort of thing
  3054.     impossible, because character collection into input lines is
  3055.     done by peripheral processors not under direct control of the
  3056.     CPU running your program.
  3057.  
  3058.     Operating system specific questions are not appropriate for
  3059.     comp.lang.c .  Many common questions are answered in
  3060.     frequently-asked questions postings in such groups as
  3061.     comp.unix.questions and comp.os.msdos.programmer .  Note that
  3062.     the answers are often not unique even across different variants
  3063.     of a system; bear in mind when answering system-specific
  3064.     questions that the answer that applies to your system may not
  3065.     apply to everyone else's.
  3066.  
  3067.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  3068.  
  3069. 16.2:    How can I find out if there are characters available for reading
  3070.     (and if so, how many)?  Alternatively, how can I do a read that
  3071.     will not block if there are no characters available?
  3072.  
  3073. A:    These, too, are entirely operating-system-specific.  Some
  3074.     versions of curses have a nodelay() function.  Depending on your
  3075.     system, you may also be able to use "nonblocking I/O", or a
  3076.     system call named "select", or the FIONREAD ioctl, or kbhit(),
  3077.     or rdchk(), or the O_NDELAY option to open() or fcntl().
  3078.  
  3079. 16.3:    How can I clear the screen?  How can I print things in inverse
  3080.     video?
  3081.  
  3082. A:    Such things depend on the terminal type (or display) you're
  3083.     using.  You will have to use a library such as termcap or
  3084.     curses, or some system-specific routines, to perform these
  3085.     functions.
  3086.  
  3087. 16.4:    How do I read the mouse?
  3088.  
  3089. A:    Consult your system documentation, or ask on an appropriate
  3090.     system-specific newsgroup (but check its FAQ list first).  Mouse
  3091.     handling is completely different under the X window system, MS-
  3092.     DOS, Macintosh, and probably every other system.
  3093.  
  3094. 16.5:    How can my program discover the complete pathname to the
  3095.     executable file from which it was invoked?
  3096.  
  3097. A:    argv[0] may contain all or part of the pathname, or it may
  3098.     contain nothing.  You may be able to duplicate the command
  3099.     language interpreter's search path logic to locate the
  3100.     executable if the name in argv[0] is present but incomplete.
  3101.     However, there is no guaranteed or portable solution.
  3102.  
  3103. 16.6:    How can a process change an environment variable in its caller?
  3104.  
  3105. A:    In general, it cannot.  Different operating systems implement
  3106.     name/value functionality similar to the Unix environment in
  3107.     different ways.  Whether the "environment" can be usefully
  3108.     altered by a running program, and if so, how, is system-
  3109.     dependent.
  3110.  
  3111.     Under Unix, a process can modify its own environment (some
  3112.     systems provide setenv() and/or putenv() functions to do this),
  3113.     and the modified environment is usually passed on to any child
  3114.     processes, but it is _not_ propagated back to the parent
  3115.     process.
  3116.  
  3117. 16.7:    How can I check whether a file exists?  I want to query the user
  3118.     if a requested output file already exists.
  3119.  
  3120. A:    You can try the access() routine, although it's got a few
  3121.     problems.  (It isn't atomic with respect to the following
  3122.     action, and it has anomalies if the program calling it is
  3123.     running as root.)
  3124.  
  3125. 16.8:    How can I find out the size of a file, prior to reading it in?
  3126.  
  3127. A:    If the "size of a file" is the number of characters you'll be
  3128.     able to read from it in C, it is in general impossible to
  3129.     determine this number in advance.  Under Unix, the stat call
  3130.     will give you an exact answer, and several other systems supply
  3131.     a Unix-like stat which will give an approximate answer.  You can
  3132.     fseek to the end and then use ftell, but this usage is
  3133.     nonportable (it gives you an accurate answer only under Unix,
  3134.     and otherwise a quasi-accurate answer only for ANSI C "binary"
  3135.     files).  Some systems provide routines called filesize or
  3136.     filelength.
  3137.  
  3138.     Are you sure you have to determine the file's size in advance?
  3139.     Since the most accurate way of determining the size of a file as
  3140.     a C program will see it is to open the file and read it, perhaps
  3141.     you can rearrange the code to learn the size as it reads.
  3142.  
  3143. 16.9:    How can a file be shortened in-place without completely clearing
  3144.     or rewriting it?
  3145.  
  3146. A:    BSD systems provide ftruncate(), several others supply chsize(),
  3147.     and a few may provide a (possibly undocumented) fcntl option
  3148.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  3149.     However, there is no truly portable solution.
  3150.  
  3151. 16.10:    How can I implement a delay, or time a user's response, with
  3152.     sub-second resolution?
  3153.  
  3154. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  3155.     systems, provided a fairly useful ftime() routine with
  3156.     resolution up to a millisecond, but it has disappeared from
  3157.     System V and Posix.  Other routines you might look for on your
  3158.     system include nap(), setitimer(), msleep(), usleep(), clock(),
  3159.     and gettimeofday().  The select() and poll() calls (if
  3160.     available) can be pressed into service to implement simple
  3161.     delays.  On MS-DOS machines, it is possible to reprogram the
  3162.     system timer and timer interrupts.
  3163.  
  3164. 16.11:    How can I read in an object file and jump to routines in it?
  3165.  
  3166. A:    You want a dynamic linker and/or loader.  It is possible to
  3167.     malloc some space and read in object files, but you have to know
  3168.     an awful lot about object file formats, relocation, etc.  Under
  3169.     BSD Unix, you could use system() and ld -A to do the linking for
  3170.     you.  Many (most?) versions of SunOS and System V have the -ldl
  3171.     library which allows object files to be dynamically loaded.
  3172.     There is also a GNU package called "dld".  See also question
  3173.     7.6.
  3174.  
  3175. 16.12:    How can I invoke an operating system command from within a
  3176.     program?
  3177.  
  3178. A:    Use system().
  3179.  
  3180.     References: K&R II Sec. B6 p. 253; ANSI Sec. 4.10.4.5; H&S
  3181.     Sec. 21.2; PCS Sec. 11 p. 179;
  3182.  
  3183. 16.13:    How can I invoke an operating system command and trap its
  3184.     output?
  3185.  
  3186. A:    Unix and some other systems provide a popen() routine, which
  3187.     sets up a stdio stream on a pipe connected to the process
  3188.     running a command, so that the output can be read (or the input
  3189.     supplied).
  3190.  
  3191.     References: PCS Sec. 11 p. 169 .
  3192.  
  3193. 16.14:    How can I read a directory in a C program?
  3194.  
  3195. A:    See if you can use the opendir() and readdir() routines, which
  3196.     are available on most Unix systems.  Implementations also exist
  3197.     for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  3198.     and FINDNEXT routines which do essentially the same thing.)
  3199.  
  3200. 16.15:    How can I do serial ("comm") port I/O?
  3201.  
  3202. A:    It's system-dependent.  Under Unix, you typically open, read,
  3203.     and write a device in /dev, and use the facilities of the
  3204.     terminal driver to adjust its characteristics.  Under MS-DOS,
  3205.     you can either use some primitive BIOS interrupts, or (if you
  3206.     require decent performance) one of any number of interrupt-
  3207.     driven serial I/O packages.
  3208.  
  3209.  
  3210. Section 17. Miscellaneous
  3211.  
  3212. 17.1:    What can I safely assume about the initial values of variables
  3213.     which are not explicitly initialized?  If global variables start
  3214.     out as "zero," is that good enough for null pointers and
  3215.     floating-point zeroes?
  3216.  
  3217. A:    Variables with "static" duration (that is, those declared
  3218.     outside of functions, and those declared with the storage class
  3219.     static), are guaranteed initialized (just once, at program
  3220.     startup) to zero, as if the programmer had typed "= 0".
  3221.     Therefore, such variables are initialized to the null pointer
  3222.     (of the correct type; see also Section 1) if they are pointers,
  3223.     and to 0.0 if they are floating-point.
  3224.  
  3225.     Variables with "automatic" duration (i.e. local variables
  3226.     without the static storage class) start out containing garbage,
  3227.     unless they are explicitly initialized.  Nothing useful can be
  3228.     predicted about the garbage.
  3229.  
  3230.     Dynamically-allocated memory obtained with malloc and realloc is
  3231.     also likely to contain garbage, and must be initialized by the
  3232.     calling program, as appropriate.  Memory obtained with calloc
  3233.     contains all-bits-0, but this is not necessarily useful for
  3234.     pointer or floating-point values (see question 3.13, and section
  3235.     1).
  3236.  
  3237. 17.2:    This code, straight out of a book, isn't compiling:
  3238.  
  3239.         f()
  3240.         {
  3241.         char a[] = "Hello, world!";
  3242.         }
  3243.  
  3244. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  3245.     initialization of "automatic aggregates" (i.e. non-static local
  3246.     arrays and structures).  As a workaround, you can make the array
  3247.     global or static.  (You can always initialize local char *
  3248.     variables with string literals, but see question 17.20).  See
  3249.     also questions 5.16 and 5.17.
  3250.  
  3251. 17.3:    How can I write data files which can be read on other machines
  3252.     with different word size, byte order, or floating point formats?
  3253.  
  3254. A:    The best solution is to use text files (usually ASCII), written
  3255.     with fprintf and read with fscanf or the like.  (Similar advice
  3256.     also applies to network protocols.)  Be skeptical of arguments
  3257.     which imply that text files are too big, or that reading and
  3258.     writing them is too slow.  Not only is their efficiency
  3259.     frequently acceptable in practice, but the advantages of being
  3260.     able to manipulate them with standard tools can be overwhelming.
  3261.  
  3262.     If you must use a binary format, you can improve portability,
  3263.     and perhaps take advantage of prewritten I/O libraries, by
  3264.     making use of standardized formats such as Sun's XDR (RFC 1014),
  3265.     OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  3266.     See also question 9.11.
  3267.  
  3268. 17.4:    How can I delete a line (or record) from the middle of a file?
  3269.  
  3270. A:    Short of rewriting the file, you probably can't.  See also
  3271.     question 16.9.
  3272.  
  3273. 17.5:    How can I return several values from a function?
  3274.  
  3275. A:    Either pass pointers to locations which the function can fill
  3276.     in, or have the function return a structure containing the
  3277.     desired values, or (in a pinch) consider global variables.  See
  3278.     also questions 2.17, 3.4, and 9.2.
  3279.  
  3280. 17.6:    If I have a char * variable pointing to the name of a function
  3281.     as a string, how can I call that function?
  3282.  
  3283. A:    The most straightforward thing to do is maintain a
  3284.     correspondence table of names and function pointers:
  3285.  
  3286.         int function1(), function2();
  3287.  
  3288.         struct {char *name; int (*funcptr)(); } symtab[] =
  3289.             {
  3290.             "function1",    function1,
  3291.             "function2",    function2,
  3292.             };
  3293.  
  3294.     Then, just search the table for the name, and call through the
  3295.     associated function pointer.  See also questions 9.9 and 16.11.
  3296.  
  3297. 17.7:    I seem to be missing the system header file <sgtty.h>.  Can
  3298.     someone send me a copy?
  3299.  
  3300. A:    Standard headers exist in part so that definitions appropriate
  3301.     to your compiler, operating system, and processor can be
  3302.     supplied.  You cannot just pick up a copy of someone else's
  3303.     header file and expect it to work, unless that person is using
  3304.     exactly the same environment.  Ask your compiler vendor why the
  3305.     file was not provided (or to send a replacement copy).
  3306.  
  3307. 17.8:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  3308.     from C?  (And vice versa?)
  3309.  
  3310. A:    The answer is entirely dependent on the machine and the specific
  3311.     calling sequences of the various compilers in use, and may not
  3312.     be possible at all.  Read your compiler documentation very
  3313.     carefully; sometimes there is a "mixed-language programming
  3314.     guide," although the techniques for passing arguments and
  3315.     ensuring correct run-time startup are often arcane.  More
  3316.     information may be found in FORT.gz by Glenn Geers, available
  3317.     via anonymous ftp from suphys.physics.su.oz.au in the src
  3318.     directory.
  3319.  
  3320.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  3321.     many popular machines.  It is available via anonymous ftp from
  3322.     zebra.desy.de (131.169.2.244).
  3323.  
  3324.     In C++, a "C" modifier in an external function declaration
  3325.     indicates that the function is to be called using C calling
  3326.     conventions.
  3327.  
  3328. 17.9:    Does anyone know of a program for converting Pascal or FORTRAN
  3329.     (or LISP, Ada, awk, "Old" C, ...) to C?
  3330.  
  3331. A:    Several public-domain programs are available:
  3332.  
  3333.     p2c    A Pascal to C converter written by Dave Gillespie,
  3334.         posted to comp.sources.unix in March, 1990 (Volume 21);
  3335.         also available by anonymous ftp from
  3336.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  3337.  
  3338.     ptoc    Another Pascal to C converter, this one written in
  3339.         Pascal (comp.sources.unix, Volume 10, also patches in
  3340.         Volume 13?).
  3341.  
  3342.     f2c    A Fortran to C converter jointly developed by people
  3343.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  3344.         about f2c, send the mail message "send index from f2c"
  3345.         to netlib@research.att.com or research!netlib.  (It is
  3346.         also available via anonymous ftp on research.att.com, in
  3347.         directory dist/f2c.)
  3348.  
  3349.     This FAQ list's maintainer also has available a list of other
  3350.     commercial translation products, and some for more obscure
  3351.     languages.
  3352.  
  3353.     See also question 5.3.
  3354.  
  3355. 17.10:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  3356.     code?
  3357.  
  3358. A:    C++ was derived from C, and is largely based on it, but there
  3359.     are some legal C constructs which are not legal C++.  (Many C
  3360.     programs will nevertheless compile correctly in a C++
  3361.     environment.)
  3362.  
  3363. 17.11:    I need:                A:  Look for programs (see also
  3364.                         question 17.12) named:
  3365.  
  3366.     a C cross-reference            cflow, calls, cscope
  3367.     generator
  3368.  
  3369.     a C beautifier/pretty-            cb, indent
  3370.     printer
  3371.  
  3372. 17.12:    Where can I get copies of all these public-domain programs?
  3373.  
  3374. A:    If you have access to Usenet, see the regular postings in the
  3375.     comp.sources.unix and comp.sources.misc newsgroups, which
  3376.     describe, in some detail, the archiving policies and how to
  3377.     retrieve copies.  The usual approach is to use anonymous ftp
  3378.     and/or uucp from a central, public-spirited site, such as uunet
  3379.     (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  3380.     or list all of the available archive sites and how to access
  3381.     them.
  3382.  
  3383.     Ajay Shah maintains an index of free numerical software; it is
  3384.     posted periodically, and available where this FAQ list is
  3385.     archived (see question 17.33).  The comp.archives newsgroup
  3386.     contains numerous announcements of anonymous ftp availability of
  3387.     various items.  The "archie" mailserver can tell you which
  3388.     anonymous ftp sites have which packages; send the mail message
  3389.     "help" to archie@quiche.cs.mcgill.ca for information.  Finally,
  3390.     the newsgroup comp.sources.wanted is generally a more
  3391.     appropriate place to post queries for source availability, but
  3392.     check _its_ FAQ list, "How to find sources," before posting
  3393.     there.
  3394.  
  3395. 17.13:    When will the next International Obfuscated C Code Contest
  3396.     (IOCCC) be held?  How can I get a copy of the current and
  3397.     previous winning entries?
  3398.  
  3399. A:    The contest typically runs from early March through mid-May.  To
  3400.     obtain a current copy of the rules and guidelines, send e-mail
  3401.     with the Subject: line "send rules" to:
  3402.  
  3403.         {apple,pyramid,sun,uunet}!hoptoad!judges  or
  3404.         judges@toad.com
  3405.  
  3406.     (Note that these are _not_ the addresses for submitting
  3407.     entries.)
  3408.  
  3409.     Contest winners are first announced at the Summer Usenix
  3410.     Conference in mid-June, and posted to the net sometime in July-
  3411.     August.  Winning entries from previous years (to 1984) are
  3412.     archived at uunet (see question 17.12) under the directory
  3413.     ~/pub/ioccc.
  3414.  
  3415.     As a last resort, previous winners may be obtained by sending
  3416.     e-mail to the above address, using the Subject: "send YEAR
  3417.     winners", where YEAR is a single four-digit year, a year range,
  3418.     or "all".
  3419.  
  3420. 17.14:    Why don't C comments nest?  How am I supposed to comment out
  3421.     code containing comments?  Are comments legal inside quoted
  3422.     strings?
  3423.  
  3424. A:    Nested comments would cause more harm than good, mostly because
  3425.     of the possibility of accidentally leaving comments unclosed by
  3426.     including the characters "/*" within them.  For this reason, it
  3427.     is usually better to "comment out" large sections of code, which
  3428.     might contain comments, with #ifdef or #if 0 (but see question
  3429.     5.11).
  3430.  
  3431.     The character sequences /* and */ are not special within
  3432.     double-quoted strings, and do not therefore introduce comments,
  3433.     because a program (particularly one which is generating C code
  3434.     as output) might want to print them.
  3435.  
  3436.     References: ANSI Appendix E p. 198, Rationale Sec. 3.1.9 p. 33.
  3437.  
  3438. 17.15:    How can I get the ASCII value corresponding to a character, or
  3439.     vice versa?
  3440.  
  3441. A:    In C, characters are represented by small integers corresponding
  3442.     to their values (in the machine's character set) so you don't
  3443.     need a conversion routine: if you have the character, you have
  3444.     its value.
  3445.  
  3446. 17.16:    How can I implement sets and/or arrays of bits?
  3447.  
  3448. A:    Use arrays of char or int, with a few macros to access the right
  3449.     bit at the right index (try using 8 for CHAR_BIT if you don't
  3450.     have <limits.h>):
  3451.  
  3452.         #include <limits.h>        /* for CHAR_BIT */
  3453.  
  3454.         #define BITMASK(bit) (1 << ((bit) % CHAR_BIT))
  3455.         #define BITSLOT(bit) ((bit) / CHAR_BIT)
  3456.         #define BITSET(ary, bit) ((ary)[BITSLOT(bit)] |= BITMASK(bit))
  3457.         #define BITTEST(ary, bit) ((ary)[BITSLOT(bit)] & BITMASK(bit))
  3458.  
  3459. 17.17:    What is the most efficient way to count the number of bits which
  3460.     are set in a value?
  3461.  
  3462. A:    This and many other similar bit-twiddling problems can often be
  3463.     sped up and streamlined using lookup tables (but see the next
  3464.     question).
  3465.  
  3466. 17.18:    How can I make this code more efficient?
  3467.  
  3468. A:    Efficiency, though a favorite comp.lang.c topic, is not
  3469.     important nearly as often as people tend to think it is.  Most
  3470.     of the code in most programs is not time-critical.  When code is
  3471.     not time-critical, it is far more important that it be written
  3472.     clearly and portably than that it be written maximally
  3473.     efficiently.  (Remember that computers are very, very fast, and
  3474.     that even "inefficient" code can run without apparent delay.)
  3475.  
  3476.     It is notoriously difficult to predict what the "hot spots" in a
  3477.     program will be.  When efficiency is a concern, it is important
  3478.     to use profiling software to determine which parts of the
  3479.     program deserve attention.  Often, actual computation time is
  3480.     swamped by peripheral tasks such as I/O and memory allocation,
  3481.     which can be sped up by using buffering and caching techniques.
  3482.  
  3483.     For the small fraction of code that is time-critical, it is
  3484.     vital to pick a good algorithm; it is less important to
  3485.     "microoptimize" the coding details.  Many of the "efficient
  3486.     coding tricks" which are frequently suggested (e.g. substituting
  3487.     shift operators for multiplication by powers of two) are
  3488.     performed automatically by even simpleminded compilers.
  3489.     Heavyhanded "optimization" attempts can make code so bulky that
  3490.     performance is degraded.
  3491.  
  3492.     For more discussion of efficiency tradeoffs, as well as good
  3493.     advice on how to increase efficiency when it is important, see
  3494.     chapter 7 of Kernighan and Plauger's The Elements of Programming
  3495.     Style, and Jon Bentley's Writing Efficient Programs.
  3496.  
  3497. 17.19:    Are pointers really faster than arrays?  How much do function
  3498.     calls slow things down?  Is ++i faster than i = i + 1?
  3499.  
  3500. A:    Precise answers to these and many similar questions depend of
  3501.     course on the processor and compiler in use.  If you simply must
  3502.     know, you'll have to time test programs carefully.  (Often the
  3503.     differences are so slight that hundreds of thousands of
  3504.     iterations are required even to see them.  Check the compiler's
  3505.     assembly language output, if available, to see if two purported
  3506.     alternatives aren't compiled identically.)
  3507.  
  3508.     It is "usually" faster to march through large arrays with
  3509.     pointers rather than array subscripts, but for some processors
  3510.     the reverse is true.
  3511.  
  3512.     Function calls, though obviously incrementally slower than in-
  3513.     line code, contribute so much to modularity and code clarity
  3514.     that there is rarely good reason to avoid them.
  3515.  
  3516.     Before rearranging expressions such as i = i + 1, remember that
  3517.     you are dealing with a C compiler, not a keystroke-programmable
  3518.     calculator.  Any decent compiler will generate identical code
  3519.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  3520.     i += 1 over i = i + 1 have to do with style, not efficiency.
  3521.     (See also question 4.7.)
  3522.  
  3523. 17.20:    Why does this code:
  3524.  
  3525.         char *p = "Hello, world!";
  3526.         p[0] = tolower(p[0]);
  3527.  
  3528.     crash?
  3529.  
  3530. A:    String literals are not necessarily modifiable, except (in
  3531.     effect) when they are used as array initializers.  Try
  3532.  
  3533.         char a[] = "Hello, world!";
  3534.  
  3535.     (For compiling old code, some compilers have a switch
  3536.     controlling whether strings are writable or not.)  See also
  3537.     questions 2.1, 2.2, 2.8, and 17.2.
  3538.  
  3539.     References: ANSI Sec. 3.1.4 .
  3540.  
  3541. 17.21:    This program crashes before it even runs!  (When single-stepping
  3542.     with a debugger, it dies before the first statement in main.)
  3543.  
  3544. A:    You probably have one or more very large (kilobyte or more)
  3545.     local arrays.  Many systems have fixed-size stacks, and those
  3546.     which perform dynamic stack allocation automatically (e.g. Unix)
  3547.     can be confused when the stack tries to grow by a huge chunk all
  3548.     at once.
  3549.  
  3550.     It is often better to declare large arrays with static duration
  3551.     (unless of course you need a fresh set with each recursive
  3552.     call).
  3553.  
  3554.     (See also question 9.4.)
  3555.  
  3556. 17.22:    What do "Segmentation violation" and "Bus error" mean?
  3557.  
  3558. A:    These generally mean that your program tried to access memory it
  3559.     shouldn't have, invariably as a result of improper pointer use,
  3560.     often involving uninitialized or improperly allocated pointers
  3561.     (see questions 3.1 and 3.2), or malloc (see question 17.23), or
  3562.     perhaps scanf (see question 11.2).
  3563.  
  3564. 17.23:    My program is crashing, apparently somewhere down inside malloc,
  3565.     but I can't see anything wrong with it.
  3566.  
  3567. A:    It is unfortunately very easy to corrupt malloc's internal data
  3568.     structures, and the resulting problems can be hard to track
  3569.     down.  The most common source of problems is writing more to a
  3570.     malloc'ed region than it was allocated to hold; a particularly
  3571.     common bug is to malloc(strlen(s)) instead of strlen(s) + 1.
  3572.     Other problems involve freeing pointers not obtained from
  3573.     malloc, or trying to realloc a null pointer (see question 3.12).
  3574.  
  3575.     A number of debugging packages exist to help track down malloc
  3576.     problems; one popular one is Conor P. Cahill's "dbmalloc,"
  3577.     posted to comp.sources.misc in September of 1992.  Others are
  3578.     "leak," available in volume 27 of the comp.sources.unix
  3579.     archives; JMalloc.c and JMalloc.h in Fidonet's C_ECHO Snippets
  3580.     (or ask archie; see question 17.12); and MEMDEBUG from
  3581.     dorado.crpht.lu in pub/sources/memdebug .  See also question
  3582.     17.12.
  3583.  
  3584. 17.24:    Does anyone have a C compiler test suite I can use?
  3585.  
  3586. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one.
  3587.     The FSF's GNU C (gcc) distribution includes a c-torture-
  3588.     test.tar.Z which checks a number of common problems with
  3589.     compilers.  Kahan's paranoia test, found in netlib/paranoia on
  3590.     netlib.att.com, strenuously tests a C implementation's floating
  3591.     point capabilities.
  3592.  
  3593. 17.25:    Where can I get a YACC grammar for C?
  3594.  
  3595. A:    The definitive grammar is of course the one in the ANSI
  3596.     standard.  Another grammar, by Jim Roskind, is in pub/*grammar*
  3597.     at ics.uci.edu .  A fleshed-out, working instance of the ANSI
  3598.     grammar (due to Jeff Lee) is on uunet (see question 17.12) in
  3599.     usenet/net.sources/ansi.c.grammar.Z (including a companion
  3600.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  3601.     the appendix to K&R II.
  3602.  
  3603.     References: ANSI Sec. A.2 .
  3604.  
  3605. 17.26:    I need code to parse and evaluate expressions.
  3606.  
  3607. A:    Two available packages are "defunc," posted to comp.source.misc
  3608.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  3609.     and available from sunsite.unc.edu in
  3610.     pub/packages/development/libraries/defunc-1.3.tar.Z; and
  3611.     "parse," at lamont.ldgo.columbia.edu.
  3612.  
  3613. 17.27:    I need a sort of an "approximate" strcmp routine, for comparing
  3614.     two strings for close, but not necessarily exact, equality.
  3615.  
  3616. A:    The traditional routine for doing this sort of thing involves
  3617.     the "soundex" algorithm, which maps similar-sounding words to
  3618.     the same numeric codes.  Soundex is described in the Searching
  3619.     and Sorting volume of Donald Knuth's classic _The Art of
  3620.     Computer Programming_.
  3621.  
  3622. 17.28:    How can I find the day of the week given the date?
  3623.  
  3624. A:    Use mktime (see questions 12.6 and 12.7), or Zeller's
  3625.     congruence.  Here is one quick implementation posted by Tomohiko
  3626.     Sakamoto:
  3627.  
  3628.         dayofweek(y, m, d)    /* 0 = Sunday */
  3629.         int y, m, d;        /* 1 <= m <= 12,  y > 1752 or so */
  3630.         {
  3631.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  3632.             y -= m < 3;
  3633.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  3634.         }
  3635.  
  3636. 17.29:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  3637.     for leap years?
  3638.  
  3639. A:    Yes and no, respectively.  The full expression for the Gregorian
  3640.     calendar is
  3641.  
  3642.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  3643.  
  3644.     See a good astronomical almanac or other reference for details.
  3645.  
  3646. 17.30:    How do you pronounce "char"?
  3647.  
  3648. A:    You can pronounce the C keyword "char" in at least three ways:
  3649.     like the English words "char," "care," or "car;" the choice is
  3650.     arbitrary.
  3651.  
  3652. 17.31:    What's a good book for learning C?
  3653.  
  3654. A:    Mitch Wright maintains an annotated bibliography of C and Unix
  3655.     books; it is available for anonymous ftp from ftp.rahul.net in
  3656.     directory pub/mitch/YABL.
  3657.  
  3658.     This FAQ list's editor maintains a collection of previous
  3659.     answers to this question, which is available upon request.
  3660.  
  3661. 17.32:    Are there any C tutorials on the net?
  3662.  
  3663. A:    There are at least two of them:
  3664.  
  3665.     "Notes for C programmers," by Christopher Sawtell,
  3666.     available from:
  3667.     svr-ftp.eng.cam.ac.uk:misc/sawtell_C.shar
  3668.     garbo.uwasa.fi:/pc/c/c-lesson.zip
  3669.     oak.oakland.edu:pub/msdos/c/LEARN-C.ZIP
  3670.     paris7.jussieu.fr:/contributions/docs
  3671.  
  3672.     Tim Love's "C for Programmers,"
  3673.     available from svr-ftp.eng.cam.ac.uk in the misc directory.
  3674.  
  3675. 17.33:    Where can I get extra copies of this list?  What about back
  3676.     issues?
  3677.  
  3678. A:    For now, just pull it off the net; it is normally posted to
  3679.     comp.lang.c on the first of each month, with an Expires: line
  3680.     which should keep it around all month.  An abridged version is
  3681.     also available (and posted), as is a list of changes
  3682.     accompanying each significantly updated version.  These lists
  3683.     can also be found in the newsgroups comp.answers and
  3684.     news.answers .  Several sites archive news.answers postings and
  3685.     other FAQ lists, including this one: two sites are rtfm.mit.edu
  3686.     (directories pub/usenet/news.answers/C-faq/ and
  3687.     pub/usenet/comp.lang.c/ ) and ftp.uu.net (directory
  3688.     usenet/news.answers/C-faq/ ).  The archie server should help you
  3689.     find others; query it for "prog C-faq".  See the meta-FAQ list
  3690.     in news.answers for more information; see also question 17.12.
  3691.  
  3692.     This list is an evolving document of questions which have been
  3693.     Frequent since before the Great Renaming, not just a collection
  3694.     of this month's interesting questions.  Older copies are
  3695.     obsolete and don't contain much, except the occasional typo,
  3696.     that the current list doesn't.
  3697.  
  3698.  
  3699. Bibliography
  3700.  
  3701. ANSI    American National Standard for Information Systems --
  3702.     Programming Language -- C, ANSI X3.159-1989 (see question 5.2).
  3703.  
  3704. JLB    Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  3705.     1982, ISBN 0-13-970244-X.
  3706.  
  3707. H&S    Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  3708.     Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.  (A
  3709.     third edition has recently been released.)
  3710.  
  3711. PCS    Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  3712.     ISBN 0-13-868050-7.
  3713.  
  3714. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  3715.     Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  3716.  
  3717. K&R I    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3718.     Language, Prentice-Hall, 1978, ISBN 0-13-110163-3.
  3719.  
  3720. K&R II    Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3721.     Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  3722.     110362-8, 0-13-110370-9.
  3723.  
  3724. Knuth    Donald E. Knuth, The Art of Computer Programming, (3 vols.),
  3725.     Addison-Wesley, 1981.
  3726.  
  3727. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  3728.     ISBN 0-201-17928-8.
  3729.  
  3730.     P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  3731.     ISBN 0-13-131509-9.
  3732.  
  3733.     Harry Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall,
  3734.     1990, ISBN 0-13-685967-4.
  3735.  
  3736. There is a more extensive bibliography in the revised Indian Hill style
  3737. guide (see question 14.3).  See also question 17.31.
  3738.  
  3739.  
  3740. Acknowledgements
  3741.  
  3742. Thanks to Jamshid Afshar, Sudheer Apte, Randall Atkinson, Dan Bernstein,
  3743. Vincent Broman, Stan Brown, Joe Buehler, Gordon Burditt, Burkhard Burow,
  3744. Conor P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill,
  3745. Paul Carter, Raymond Chen, Jonathan Coxhead, Lee Crawford, Steve Dahmer,
  3746. Andrew Daviel, James Davies, Jutta Degener, Norm Diamond, Jeff Dunlop,
  3747. Ray Dunn, Stephen M. Dunn, Michael J. Eager, Dave Eisen, Bjorn Engsig,
  3748. Chris Flatters, Rod Flores, Alexander Forst, Jeff Francis, Dave
  3749. Gillespie, Samuel Goldstein, Alasdair Grant, Ron Guilmette, Doug Gwyn,
  3750. Tony Hansen, Joe Harrington, Guy Harris, Elliotte Rusty Harold, Jos
  3751. Horsmeier, Blair Houghton, Ke Jin, Kirk Johnson, Larry Jones, Kin-ichi
  3752. Kitano, Peter Klausler, Andrew Koenig, Tom Koenig, Ajoy Krishnan T,
  3753. Markus Kuhn, John Lauro, Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee,
  3754. Don Libes, Christopher Lott, Tim Love, Tim McDaniel, Stuart MacMartin,
  3755. John R. MacMillan, Bob Makowski, Evan Manning, Barry Margolin, George
  3756. Matas, Brad Mears, Bill Mitchell, Mark Moraes, Darren Morby, Ken Nakata,
  3757. Landon Curt Noll, David O'Brien, Richard A. O'Keefe, Hans Olsson, Philip
  3758. (lijnzaad@embl-heidelberg.de), Christopher Phillips, Francois Pinard,
  3759. Dan Pop, Kevin D. Quitt, Pat Rankin, J. M. Rosenstock, Erkki Ruohtula,
  3760. Tomohiko Sakamoto, Rich Salz, Chip Salzenberg, Paul Sand, DaviD
  3761. W. Sanderson, Christopher Sawtell, Paul Schlyter, Doug Schmidt, Rene
  3762. Schmit, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry Spencer,
  3763. David Spuler, Melanie Summit, Erik Talvola, Clarke Thatcher, Wayne
  3764. Throop, Chris Torek, Andrew Tucker, Goran Uddeborg, Rodrigo Vanegas, Jim
  3765. Van Zandt, Wietse Venema, Ed Vielmetti, Larry Virden, Chris Volpe, Mark
  3766. Warren, Larry Weiss, Freek Wiedijk, Lars Wirzenius, Dave Wolverton,
  3767. Mitch Wright, Conway Yee, and Zhuo Zang, who have contributed, directly
  3768. or indirectly, to this article.  Special thanks to Karl Heuer, and
  3769. particularly to Mark Brader, who (to borrow a line from Steve Johnson)
  3770. have goaded me beyond my inclination, and occasionally beyond my
  3771. endurance, in relentless pursuit of a better FAQ list.
  3772.  
  3773.                     Steve Summit
  3774.                     scs@eskimo.com
  3775.  
  3776. This article is Copyright 1988, 1990-1994 by Steve Summit.
  3777. It may be freely redistributed so long as the author's name, and this
  3778. notice, are retained.
  3779. The C code in this article (vstrcat(), error(), etc.) is public domain
  3780. and may be used without restriction.
  3781.